LeetCode题解: Reverse Nodes in k-Group

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.

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=1的情况。在k不等于1的时候,每次取k个结点到缓冲中去,然后更新除第一个结点之外其他结点的next指针。第一个结点的next指针指向下一个尚未处理的结点。然后继续处理。如果之后又读取了k个链表结点,那么就要更新之前的next指针。

题解:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup (ListNode* head, int k)
    {
        if (head == nullptr)
            return nullptr;
            
        if (k == 1)
            return head;
            
        vector<ListNode*> buffer (k, nullptr);
        
        ListNode* last = nullptr;
        ListNode* iter = head;
        bool first_time = true;
        for (;;)
        {
            bool terminating = false;
            
            for (int i = 0; i < k; ++i)
            {
                if (iter == nullptr)
                {
                    terminating = true;
                    break;
                }
                buffer[i] = iter;
                iter = iter->next;
            }
            
            if (terminating)
                break;
            
            for (int i = k - 1; i > 0; --i)
                buffer[i]->next = buffer[i - 1];
                
            if (last != nullptr)
                last->next = buffer.back();
    
            last = buffer.front();
            last->next = iter;
    
            if (first_time) // update head
            {
                head = buffer.back();
                first_time = false;
            }
        }
        return head;
    }
};


你可能感兴趣的:(LeetCode)