Sunday, July 10, 2016

25. Reverse Nodes in k-Group

The trick I noticed here is the first node of sublist will be the end of the new list and will be the new "dummy" node for the next new list. And we mustn't forget the end node's next should be updated every time we reverse the sublist.

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:      if (k <= 1) return head;  
13:      ListNode *dummy = new ListNode(0);  
14:      dummy->next = head;  
15:      ListNode *prev = dummy, *cur = prev->next;  
16:      while (cur) {  
17:        int count = k;  
18:        while (cur && count) {  
19:          cur = cur->next;  
20:          count--;  
21:        }  
22:        if (count) break;  
23:        ListNode *end = prev->next;  
24:        ListNode *p = end->next;  
25:        while (p != cur) {  
26:          end->next = p->next;  
27:          p->next = prev->next;  
28:          prev->next = p;  
29:          p = end->next;  
30:        }  
31:        prev = end;  
32:      }  
33:      head = dummy->next;  
34:      delete dummy;  
35:      return head;  
36:    }  
37:  };  

No comments:

Post a Comment