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.

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.

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

分析:

这个题目逻辑要记住以下几点:

(1) 判断的时候都是curr == NULL,因为如果用curr->next == NULL的话对k == n的情况不适用。

(2) 用curr == NULL来break for循环之后要接一个curr == NULL来break while循环,并且在break while之前需要把没有反序的剩余链表连上。

解法:

class Solution {
public:
    /**
     * @param head a ListNode
     * @param k an integer
     * @return a ListNode
     */

    ListNode* reverseList(ListNode* head) {
        ListNode dummy(0);
        dummy.next = head;

        while (head->next != NULL) {
            ListNode* next = head->next;
            head->next = next->next;
            next->next = dummy.next;
            dummy.next = next;
        }

        return dummy.next;
    } 

    ListNode *reverseKGroup(ListNode *head, int k) {
        // Write your code here
        if (head == NULL || head->next == NULL) {
            return head;
        }

        if (k == 0) {
            return head;
        }

        ListNode dummy(0);
        ListNode* tail = &dummy;
        ListNode* curr = head;
        ListNode* newHead = head;

        while (curr != NULL) {

            for (int i = 0; i < k - 1; i++) {
                if (curr == NULL) {
                    //tail->next = newHead;
                    break;
                }
                curr = curr->next;
            }

            if (curr == NULL) {
                tail->next = newHead;
                break;
            }

            newHead = curr->next;
            curr->next = NULL;

            tail->next = reverseList(head);
            while (tail->next != NULL) {
                tail = tail->next;
            }

            head = newHead;
            curr = newHead;

        }

        return dummy.next;
    }
};

results matching ""

    No results matching ""