描述
将给出的链表中的节点每 k 个一组翻转,返回翻转后的链表
如果链表中的节点数不是 k 的倍数,将最后剩下的节点保持原样
你不能更改节点中的值,只能更改节点本身。
要求空间复杂度 O(1),时间复杂度 O(n)
例如:
给定的链表是 1→2→3→4→5
对于 k = 2 , 应该返回 2→1→4→3→5
对于 k = 3 , 应该返回 3→2→1→4→5
解题思路
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
if(head==nullptr || head->next==nullptr || k<2) return head;
ListNode* dummy = new ListNode(0);
dummy->next = head;
int len = 0;
ListNode* pre = dummy;
ListNode* cur = head;
ListNode* nex = nullptr;
while(cur!=nullptr){
len++;
cur = cur->next;
}
cur = head;
for(int i=1;i<=len/k;i++){
for(int j=1;j<k;j++){
nex = cur->next;
cur->next = nex->next;
nex->next = pre->next;
pre->next = nex;
}
if(i==1) dummy->next = pre->next;
pre = cur;
cur = cur->next;
}
return dummy->next;
}
};