[LeetCode] Reverse Nodes in k-Group 每k個一組翻轉連結串列

Grandyang發表於2015-04-20

 

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.

 

這道題讓我們以每k個為一組來翻轉連結串列,實際上是把原連結串列分成若干小段,然後分別對其進行翻轉,那麼肯定總共需要兩個函式,一個是用來分段的,一個是用來翻轉的,我們就以題目中給的例子來看,對於給定連結串列1->2->3->4->5,一般在處理連結串列問題時,我們大多時候都會在開頭再加一個dummy node,因為翻轉連結串列時頭結點可能會變化,為了記錄當前最新的頭結點的位置而引入的dummy node,那麼我們加入dummy node後的連結串列變為-1->1->2->3->4->5,如果k為3的話,我們的目標是將1,2,3翻轉一下,那麼我們需要一些指標,pre和next分別指向要翻轉的連結串列的前後的位置,然後翻轉後pre的位置更新到如下新的位置:

 

-1->1->2->3->4->5
 |        |  |
pre      cur next

-1->3->2->1->4->5
    |     |  |
   cur   pre next

 

以此類推,只要cur走過k個節點,那麼next就是cur->next,就可以呼叫翻轉函式來進行區域性翻轉了,注意翻轉之後新的cur和pre的位置都不同了,那麼翻轉之後,cur應該更新為pre->next,而如果不需要翻轉的話,cur更新為cur->next,程式碼如下所示:

 

解法一:

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (!head || k == 1) return head;
        ListNode *dummy = new ListNode(-1), *pre = dummy, *cur = head;
        dummy->next = head;
        for (int i = 1; cur; ++i) {
            if (i % k == 0) {
                pre = reverseOneGroup(pre, cur->next);
                cur = pre->next;
            } else {
                cur = cur->next;
            }
        }
        return dummy->next;
    }
    ListNode* reverseOneGroup(ListNode* pre, ListNode* next) {
        ListNode *last = pre->next, *cur = last->next;
        while(cur != next) {
            last->next = cur->next;
            cur->next = pre->next;
            pre->next = cur;
            cur = last->next;
        }
        return last;
    }
};

 

我們也可以在一個函式中完成,我們首先遍歷整個連結串列,統計出連結串列的長度,然後如果長度大於等於k,我們開始交換節點,當k=2時,每段我們只需要交換一次,當k=3時,每段需要交換2此,所以i從1開始迴圈,注意交換一段後更新pre指標,然後num自減k,直到num<k時迴圈結束,參見程式碼如下:

 

解法二:

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode *dummy = new ListNode(-1), *pre = dummy, *cur = pre;
        dummy->next = head;
        int num = 0;
        while (cur = cur->next) ++num;
        while (num >= k) {
            cur = pre->next;
            for (int i = 1; i < k; ++i) {
                ListNode *t = cur->next;
                cur->next = t->next;
                t->next = pre->next;
                pre->next = t;
            }
            pre = cur;
            num -= k;
        }
        return dummy->next;
    }
};

 

我們也可以使用遞迴來做,我們用head記錄每段的開始位置,cur記錄結束位置的下一個節點,然後我們呼叫reverse函式來將這段翻轉,然後得到一個new_head,原來的head就變成了末尾,這時候後面接上遞迴呼叫下一段得到的新節點,返回new_head即可,參見程式碼如下:

 

解法三:

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode *cur = head;
        for (int i = 0; i < k; ++i) {
            if (!cur) return head;
            cur = cur->next;
        }
        ListNode *new_head = reverse(head, cur);
        head->next = reverseKGroup(cur, k);
        return new_head;
    }
    ListNode* reverse(ListNode* head, ListNode* tail) {
        ListNode *pre = tail;
        while (head != tail) {
            ListNode *t = head->next;
            head->next = pre;
            pre = head;
            head = t;
        }
        return pre;
    }
};

 

類似題目:

Swap Nodes in Pairs

 

參考資料:

https://leetcode.com/problems/reverse-nodes-in-k-group/

https://leetcode.com/problems/reverse-nodes-in-k-group/discuss/11435/C%2B%2B-Elegant-and-Small

https://leetcode.com/problems/reverse-nodes-in-k-group/discuss/11457/20-line-iterative-C%2B%2B-solution

https://leetcode.com/problems/reverse-nodes-in-k-group/discuss/11440/Non-recursive-Java-solution-and-idea

https://leetcode.com/problems/reverse-nodes-in-k-group/discuss/11423/Short-but-recursive-Java-code-with-comments

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章