LeetCode - H - 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

解法

  • 記錄已完成交換段的尾節點
  • 記錄待交換段的尾節點

實現

/**
 * 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 == NULL || head->next == NULL) return head;
        ListNode* cur = head;
        ListNode* pre = NULL;
        while(cur != NULL){
            int idx = 1;
            while(idx < k && cur != NULL){
                ++idx;
                cur = cur->next;
            }
            if(idx <= k && cur == NULL) break; //注意點
            ListNode* cnext = cur->next;//注意點
            ListNode* scur = head;
            if(pre != NULL) scur = pre->next;
            while(scur->next != cnext){
                ListNode* next = scur->next;
                scur->next = next->next;
                if(pre == NULL){
                    next->next = head;
                    head = next;
                }else{
                    next->next = pre->next;
                    pre->next = next;
                }
            }
            pre = scur;
            cur = scur->next;
        }
        return head;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章