题目:
给你单链表的头指针?head
?和两个整数?left
?和?right
?,其中?left <= right
?。请你反转从位置?left
?到位置?right
?的链表节点,返回?反转后的链表?。
方法:灵神 反转链表
代码:
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy = new ListNode(0, head), p0 = dummy;
int n = left - 1;
while (n-- > 0) {
p0 = p0.next; // p0 保存开始翻转的前一个节点,后面操作需要用到
}
ListNode pre = null, cur = p0.next;
for (int i = 0; i < (right - left + 1); i++) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
p0.next.next = cur;
p0.next = pre;
return dummy.next;
}
}