1.题目
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
2.题意
分段反转链表,每段k个结点
3.分析
遍历链表,得到链表的长度num
num>=k,则开始交换节点
当k=2时,每段需要交换1次
当k=3时,每段需要交换2次
所以i从1开始循环k-1次
每完成一段后更新pre指针,
且num减去k直到num<k
总体来说每个结点会被访问两次
总时间复杂度为O(2*n)=O(n),空间复杂度为O(1)
注意不要遗漏dummy->next = head;
以及t->next = prev->next;不要写成t->next = cur;
4.代码
// 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) {
ListNode *dummy = new ListNode(-1);
ListNode *prev = dummy;
ListNode *cur = dummy;
dummy->next = head;
int num = 0;
while(cur->next != nullptr)
{
cur = cur->next;
++num;
}
while(num >= k)
{
cur = prev->next;
for(int i = 1; i < k; ++i)
{
ListNode *t = cur->next;
cur->next = t->next;
t->next = prev->next;
prev->next = t;
}
prev = cur;
num -= k;
}
return dummy->next;
}
};