leetcode Reverse Nodes in k-Group

Two problems: 

1. Counting the length is much easier than reversing the last less than k nodes. 

2.  Don't forget:

lastGroupTail->next = p;
 
 

 

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
 public:
  ListNode *reverseKGroup(ListNode *head, int k) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    if (k <= 1 || head == NULL)
      return head;
    ListNode* dummy = new ListNode(0);
    dummy->next = head;
    ListNode *p = head, *last = NULL, *next = NULL, *lastGroupTail = dummy, *curGroupTail = NULL, *res = NULL;
    int count = 1, len = 0;
    for(p = head; p != NULL; p = p->next, ++len);
    p = head;
    int countmax = len / k * k;
    while (p != NULL && count <= countmax) {
      next = p->next;
      if (count % k == 1)
        curGroupTail = p;
      else if (count % k == 0) {
        lastGroupTail->next = p;
        lastGroupTail = curGroupTail;
      }
      p->next = last;
      ++count;
      last = p;
      p = next;
    }
    lastGroupTail->next = p;
    res = dummy->next;
    return res;
  }
};


 

 

你可能感兴趣的:(LeetCode)