[LeetCode] 25. Reverse Nodes in k-Group

題目鏈接: https://leetcode.com/problems/reverse-nodes-in-k-group/description/

Description

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.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For 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

解題思路

題意大致爲,將鏈表每 k 個結點分爲一組,每組進行反轉,並且剩下的不足 k 個結點的組不處理。

組數可以通過先計算鏈表長度 len,然後用 len / k 獲得。

當前組的頭 cur_h 從鏈表頭開始,先計算下一組的頭的指針 next_h,然後在 cur_hnext_h 範圍內反轉結點。

這個步驟跟整個鏈表反轉是一樣的,只是終止條件的判斷不是 NULL,而是 next_h,另外這個步驟要使得 cur_h->next = next_h,這樣確保了最後不足 k 個結點的組也被連上。

最後,將上一組的尾結點 last_hnext 指針指向當前組反轉後的頭結點指針,並且更新 last_hcur_h 指針。

空間複雜度爲 O(1)

Code

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        int len = 0;
        // 上一組未反轉前的頭
        ListNode* last_h = NULL;
        // 當前組未反轉前的頭
        ListNode* cur_h = head;
        // 下一組未反轉前的頭
        ListNode* next_h;
        ListNode *p, *q, *r;

        // 計算鏈表長度
        while (cur_h != NULL) {
            len++;
            cur_h = cur_h->next;
        }

        // n 爲組數
        int n = len / k;
        cur_h = head;
        for (int i = 0; i < n; ++i) {
            // 計算下一組未反轉前的頭結點指針
            next_h = cur_h;
            for (int j = 0; j < k; ++j) {
                next_h = next_h->next;
            }

            // 開始反轉
            q = next_h;
            p = cur_h;
            while (p != next_h) {
                r = p->next;
                p->next = q;
                q = p;
                p = r;
            }

            // 將上一組的尾結點連到當前組反轉後的頭
            if (last_h != NULL) {
                last_h->next = q;
            } else {
                head = q;
            }

            last_h = cur_h;
            cur_h = next_h;
        }

        return head;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章