LeetCode92. 反转链表 II
反转从位置 m
到 n
的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
解题思路
//思路与上题day01 反转链表类似,只是这里将第m-1
个位置换成了上题的dummy
Java代码
/**
* 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 reverseBetween(ListNode head, int m, int n) {
//思路与206题反转链表类似,只是这里将第m-1个位置换成了那题的dummy
if(head == null || head.next == null) return head;
//建立虚拟头结点,方便对所有结点的操作统一
ListNode dummy = new ListNode(-1);
dummy.next = head;
//本题使用头插法的首结点应该为第m-1个结点
ListNode pre = dummy;
for(int i = 0;i < m - 1;i++){
pre = pre.next;
}
//接下来的操作用206题一致
ListNode tail =pre.next;
ListNode cur = tail.next;
//头插后面的 n - m个结点到pre之后即可
for(int i = m;i < n;i++){
ListNode nxt = cur.next;
cur.next = pre.next;
pre.next = cur;
tail.next = nxt;
cur = nxt;
}
return dummy.next;
}
}