description:
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.
Note:
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
my answer:
画图,没有难点,就是来回挪,一个循环找组,就是找到k个数看有没有,另一个函数在组内翻转,翻转的原理就是一个一个的把节点挪到第一个的位置上,其他的后挪。
大佬的answer:
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (!head || k == 1) return head;//这里是返回原列表不是返回NULL
ListNode *dummy = new ListNode(-1), *pre = dummy, *cur = head;//这里cur = head,而不是cur = pre->next,因为此时pre的下一个是啥不知道,之后才会定义
dummy->next = head;
for (int i = 1; cur; ++i) {//这里是从1开始,条件是cur有意义,这里的i并没有传统意义上的计数,而是一个外部的技术,迭代的不是i,是cur
if (i % k == 0) {
pre = reverseOneGroup(pre, cur->next);
cur = pre->next;
} else {
cur = cur->next;
}
}
return dummy->next;
}
ListNode* reverseOneGroup(ListNode* pre, ListNode* next) {
ListNode *last = pre->next, *cur = last->next;
while(cur != next) {
last->next = cur->next;
cur->next = pre->next;
pre->next = cur;
cur = last->next;
}
return last;
}
};