题目描述:
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
大题思路如下:
翻转局部链表,也就是简单的翻转链表
1.定一个傀儡节点temp,让pre 和 cur执行傀儡节点;
2.让cur先走k步,然后让start指向per.next,end指向cur,cur指向cur.next;
3.翻转局部后,在重新拼接
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || head.next == null) return head;
ListNode temp = new ListNode(-1);
temp.next = head;
ListNode cur = temp;
ListNode pre = temp;
while(cur.next != null){
int n = k;
while(n != 0){
cur = cur.next;
if(cur == null){
return temp.next;
}
n--;
}
ListNode start = pre.next;
ListNode end = cur;
cur = cur.next;
end.next = null;
pre.next = reverse(start);
start.next = cur;
pre = start;
cur = pre;
end = pre;
}
return temp.next;
}
public ListNode reverse(ListNode head){
ListNode cur = null;
ListNode curNext = head;
while(curNext != null ){
ListNode next = curNext.next;
curNext.next = cur;
cur = curNext;
curNext = next;
}
return cur;
}
}