LeetCode-25. 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.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

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

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list's nodes, only nodes itself may be changed.

题解:

直接用容器:

class Solution {
public:
  ListNode* reverseKGroup(ListNode* head, int k) {
    if (head == NULL || head->next == NULL || k <= 1) {
      return head;
    }
    ListNode *p = head;
    vector data;
    int n = 0;
    while (p != NULL) {
      data.push_back(p->val);
      p = p->next;
      n++;
    }
    if (n < k) {
      return head;
    }
    for (int i = 0; i <= n - k; i += k) {
      reverse(data.begin() + i, data.begin() + i + k);
    }
    ListNode *q = new ListNode(data[0]);
    p = q;
    for (int i = 1; i < n; i++) {
      q->next = new ListNode(data[i]);
      q = q->next;
    }
    return p;
  }
};

递归求解:

先判断当前链长是否大于等于k,然后翻转。

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (head == NULL) {
            return NULL;
        }
        ListNode *t = head, *root = head;
        for (int i = 0; i < k - 1; i++) {
            if (t != NULL) {
                t = t->next;
            }
        }
        if (t != NULL) {
            int num = k;
            ListNode *p = head, *r = head->next;
            while (num > 1) {
                if (r != NULL) {
                    p = r;
                    r = r->next;
                    p->next = root;
                    root = p;
                }
                num--;
            }  
            head->next = reverseKGroup(r, k); 
        }
        return root;
    }
};

 

你可能感兴趣的:(LeetCode)