lc25 k个一组反转单链表
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0, head);
ListNode pre = dummy;
while (head != null) {
ListNode tail = head;
for (int i = 0; i < k - 1; i++) {
tail = tail.next;
if (tail == null) {
return dummy.next;
}
}
ListNode nextHead = tail.next;
ListNode[] reverse = reverse(head, tail);
pre.next = reverse[0];
reverse[1].next = nextHead;
head = nextHead;
pre = reverse[1];
}
return dummy.next;
}
public ListNode[] reverse(ListNode head, ListNode tail) {
ListNode pre = null;
// pre 可以赋值为tail.next;上面的reserve[1].next=nextHead的语义是一致的,把新尾部连接到原尾部的后继
ListNode p = head;
// 这里pre判断条件为链表的尾部,p的判断条件为链表尾部的后继,这次第一次做错在这里 mark一下
while (pre != tail) {
ListNode next = p.next;
p.next = pre;
pre = p;
p = next;
}
return new ListNode[]{tail, head};
}
}
链表经典题(说基础题确实不合适),里面操作不复杂,思路细致一些即可
标签:pre,head,ListNode,lc,0928,top,next,tail,reverse From: https://www.cnblogs.com/beichuang/p/16739780.html