【LeetCode算法練習(C++)】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.
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

鏈接:Reverse Nodes in k-Group

解法:設置虛擬頭結點便於操作,每輪檢查是否還有足夠的節點可供轉置,之後轉化爲鏈表轉置問題。時間O(n)


class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (k < 2) return head;
        ListNode* h = new ListNode(0);
        h->next = head;
        ListNode* p = h;
        while (enoughNode(p, k)) {
            ListNode* p1 = p->next;
            ListNode* p2 = p1->next;
            ListNode* p3 = p2->next;
            ListNode* nxt = p;
            for (int i = 0; i < k; i++) {
                nxt = nxt->next;
            }
            p1->next = nxt->next;
            nxt = p1;
            for (int i = 0; i < k - 1; i++) {
                p2->next = p1;
                p1 = p2;
                p2 = p3;
                if (p3) p3 = p3->next;
            }
            p->next = p1;
            p = nxt;
        }
        ListNode* tmp = h;
        h = h->next;
        delete(tmp);
        return h;
    }
    bool enoughNode(ListNode* head, int k) {
        for (int i = 0; i < k; i++) {
            if (!head->next) return false;
            head = head->next;
        }
        return true;
    }
};

Runtime: 36 ms

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