/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode start = head;
ListNode end = teamEnd(k, start);
if (end == null) {
return head;
}
head = end;
reverse(start, end);
ListNode lastTeamEnd = start;
while (lastTeamEnd.next != null) {
start = lastTeamEnd.next;
end = teamEnd(k, start);
if (end == null) {
return head;
}
reverse(start, end);
lastTeamEnd.next = end;
lastTeamEnd = start;
}
return head;
}
public static ListNode teamEnd(int k, ListNode s) {
while (--k != 0 && s != null) {
s = s.next;
}
return s;
}
public static void reverse(ListNode s, ListNode e) {
e = e.next;
ListNode pre = null, next = null, cur = s;
while (cur != e) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
s.next = e;
}
}
leetcode-25.k个一组翻转链表
最新推荐文章于 2024-06-06 11:58:07 发布