LeetCode 25. Reverse Nodes in k-Group
1 class Solution { 2 public: 3 ListNode* reverseKGroup(ListNode* head, int k) { 4 if(head == NULL || head->next == NULL || k == 1) return head; 5 bool flag = true; 6 ListNode* res = head; 7 ListNode* prev = NULL; 8 while(head){ 9 int num = k; 10 ListNode* start = head, * end = new ListNode(0); 11 12 while(num != 0 && head){ 13 head = head->next; 14 --num; 15 if(num == 1) end = head; 16 } 17 18 if(num != 0) break;//!! 19 end->next = NULL;//!! 20 21 ListNode* p = head, * cur = start; 22 while(cur){ 23 ListNode* tmp = cur->next; 24 cur->next = p; 25 p = cur; 26 cur = tmp; 27 } 28 if(prev) {prev->next = end;prev = start;} 29 30 if(flag){ 31 res = p;//res = end; 32 prev = start; 33 flag = false; 34 } 35 } 36 37 return res; 38 } 39 };
注意标记了!!的两行代码不能调换,否则RE.因为如果输入是[1,2], k = 3,那么在while循环里num=1时,end=NULL,end->next引起RE.
思路:先通过while循环得到要翻转的起始和末尾节点start、end,进行翻转,并和上一段节点的末尾prev,下一段节点的起始head相连。
代码又臭又长,应改进为更简洁的代码,留坑。