题目
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入: head = [1,2,3,4,5], left = 2, right = 4
输出: [1,4,3,2,5]
题解
方式一:迭代
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy = new ListNode(0, head);
// 找到起始位置
ListNode pre = null;
ListNode cur = dummy;
for (int i = 0; i < left; i++) {
pre = cur;
cur = cur.next;
}
// 每次反转一个节点,pre和cur不变
ListNode next = null;
for (int i = 0; i < right - left; i++) {
next = cur.next;
cur.next = next.next;
next.next = pre.next;
pre.next = next;
}
return dummy.next;
}
方式二:迭代
public ListNode reverseBetween(ListNode head, int left, int right) {
if (left == right) return head;
ListNode dummy = new ListNode(0, head);
ListNode pre = null; // 需要反转的前一个节点
ListNode cur = dummy;
for (int i = 0; i < left; i++) {
pre = cur;
cur = cur.next;
}
ListNode reverseHead = cur; // 需要反转的第一个节点
ListNode next = null; // 需要反转的后一个节点
for (int i = 0; i < right - left; i++) {
cur = cur.next;
next = cur.next;
}
cur.next = null; // 截断链表开始反转
ListNode newHead = reverse(reverseHead);
pre.next = newHead; // pre指向新的头节点
reverseHead.next = next; // 需要反转的第一个节点指向需要反转的后一个节点
return dummy.next;
}
ListNode reverse(ListNode head) {
ListNode cur = head;
ListNode pre = null;
ListNode next = null;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
总结
算法:迭代