做92. 反转链表 II就顺手把这个做了
class Solution {
public ListNode reverseList(ListNode head) {
ListNode trick = new ListNode(0);
trick.next = head;
reverse(trick, Integer.MAX_VALUE);
return trick.next;
}
// 反转front(不包括from)其后的k个节点
private ListNode reverse(ListNode front, int k) {
ListNode from = front.next;
if (from == null) return front;
ListNode head = from;
ListNode cur = from.next;
ListNode tmp = null;
while (k > 1 && cur != null) {
tmp = cur.next;
cur.next = from;
from = cur;
cur = tmp;
k--;
}
head.next = cur;
front.next = from;
return head;
}
}