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

此題和Swap Nodes in Pairs類似,只是這不再是swap 2個了,而變成K個一次;但是思路還是可以借鑑的,bnode用來只是當前段的前一個node, curStartNode用來表示當前段的起始位置,knode用來表示當前段的最後一個節點,這三個節點跟Swap Nodes in Pairs一樣的操作;除了操作這三個node之外,還需要將當前段整個的反轉,這要用到Reverse Linked List的做法,直接在用三個指針反轉鏈表,這個反轉也是一個curNode表示當前要反轉的鏈表,curbnode表示curNode的前一個node, nextNode用來表示curNode的下一個節點,交換指針next可以實現就地反轉;有了這兩個操作之後,自然就可以很好的解決這個問題了。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    //類似於Swap Node in pairs,只是這裏是swap k 個一次
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(head == NULL)
            return NULL;
        if(k == 1)
            return head;
        ListNode *bNode = head, *knode = head, *curStartNode = head;
        while(knode != NULL)
        {
            int count = 1;
            while(knode != NULL && count < k)
            {
                knode = knode->next;
                if(knode != NULL)
                    ++count;
            }
            
            if(count == k)
            {
                //反轉
                ListNode *curbnode = curStartNode, *curNode = curStartNode->next, *nextNode = NULL;
                while(curNode != knode)
                {
                    nextNode = curNode->next;
                    curNode->next = curbnode;
                    curbnode = curNode;
                    curNode = nextNode;
                }
                
                //連接
                curStartNode->next = knode->next;
                knode->next = curbnode;
                if(bNode == head)
                {
                    head = knode;
                }
                else
                {
                    bNode->next = knode;
                }
                
                bNode = curStartNode;
                knode = bNode->next;
                curStartNode = bNode->next;
            }
        }
        
        return head;
    }
};


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