1. 程式人生 > 實用技巧 >LeetCode 92. 反轉連結串列 II

LeetCode 92. 反轉連結串列 II

題目連線

92. 反轉連結串列 II

題目分析

題目要求我們用一趟掃描完成旋轉,我們只需要先把[m,n]這段區間內的連結串列定位了就容易做了。當我們完成定位後就是普通的三指標反轉連結串列

程式碼實現

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode fast = head;
        int count = 1;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode slow = dummy;
        while(fast != null){
            if(count < m){
                slow = slow.next;
            }
            fast = fast.next;
            count++;
            if(count == n){
                ListNode tail = fast.next;
                fast.next = null;
                ListNode node = slow.next;
                slow.next = null;
                fast = node;
                ListNode cur = node;
                ListNode post = null;
                while(fast != null){
                    fast = fast.next;
                    cur.next = post;
                    post = cur;
                    cur = fast;
                }
                slow.next = post;
                node.next = tail;
                return dummy.next;
            }
        }
        return head;
    }
}