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;
    }
}
posted @ 2020-10-04 18:12  ZJPang  阅读(99)  评论(0编辑  收藏  举报