Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.You may not alter the values in the nodes, only nodes itself may be changed.Only constant memory is allowed.
For example,Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
这个题目的复杂在单链表但是需要回溯,我做的很简单,就是每K个作为一个循环,在循环内反转链表的val,思路简单,只对链表的value进行修改反转。
代码:
1 ListNode* reverseKGroup(ListNode* head, int k) 2 { 3 if (k<=1) 4 { 5 return head; 6 } 7 if (head==NULL) 8 { 9 return head; 10 } 11 if (head->next==NULL) 12 { 13 return head; 14 } 15 ListNode* p=head; 16 ListNode* q=head; 17 ListNode* m=head; 18 while(p->next!=NULL) 19 { 20 q=p; 21 for(int i=0;i<k-1;i++) 22 { 23 if (p->next!=NULL) 24 { 25 p=p->next; 26 } 27 else 28 return head; 29 } 30 m=p; 31 for(int j=0;j<k/2;j++) 32 { 33 int temp=m->val; 34 m->val=q->val; 35 q->val=temp; 36 q=q->next; 37 38 m=q; 39 for(int i=0;i<k-2*j-3;i++) 40 m=m->next; 41 } 42 if (p->next!=NULL) 43 { 44 p=p->next; 45 } 46 else 47 return head; 48 } 49 return head; 50 }
leetcode 25: Reverse Nodes in k-Group
原文:http://www.cnblogs.com/zhang-hill/p/5063921.html