【leetcode】Reverse Nodes in k-Group
Reverse Nodes in k-Group
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个元素为一个分组进行翻转
确定元素是否足够k个,如果足够,进行翻转(每次把当前元素移动到开头位置)
如果不够保持原样
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *reverseKGroup(ListNode *head, int k) { 12 13 if(k<=1) return head; 14 15 ListNode *front=new ListNode(0); 16 front->next=head; 17 18 ListNode *cur,*next,*result; 19 cur=head; 20 result=head; 21 22 23 while(cur!=NULL) 24 { 25 int count=1; 26 ListNode *tmp=cur; 27 28 //当前元素以及后续元素之和是否够k个 29 while(cur!=NULL) 30 { 31 cur=cur->next; 32 if(cur==NULL) break; 33 34 count++; 35 if(count==k) 36 { 37 break; 38 } 39 } 40 41 42 43 if(count==k) 44 { 45 //此时cur指向需要翻转的最后一个元素,last表示下次开始时的元素 46 ListNode *last=cur->next; 47 cur=tmp; 48 49 //表示是否需要更新头结点,作为返回值 50 bool isfirst=front->next==head; 51 52 //每次把当前的元素移动到开头 53 while(cur->next!=last) 54 { 55 //获得下一个元素 56 next=cur->next; 57 //当前元素指向下下个元素 58 cur->next=next->next; 59 //下一个元素移动到开头 60 next->next=front->next; 61 //指向开头元素 62 front->next=next; 63 64 if(isfirst) result=front->next; 65 } 66 } 67 else 68 { 69 break; 70 } 71 72 front=cur; 73 cur=last; 74 } 75 76 return result; 77 } 78 };