LeetCode

来源:互联网 发布:最好的网络推广公司 编辑:程序博客网 时间:2024/05/22 17:06

题意

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->5For k = 2, you should return: 2->1->4->3->5For 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;    }};
0 0
原创粉丝点击