92. Reverse Linked List 2

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

解析:将链表从m到n倒序,其实本质上是复杂版的插入排序

试想有一个链表1 2 3 4 5 6,m = 2, n = 4.

1. 1 3 2 4 5 6

2. 1 4 3 2 5 6

第一次将3插入在1后

第二次将4插入在1后

这样分析可以得出,1和2的位置其实是不变的,只要不停地将序列内的元素插入到1之后就可以了

设1为pre,即倒叙链表的前一位元素

设2位start,即倒叙链表的第一位元素

设遍历位是move,即要插入的元素

move = start.next;  定位move

接下来三步可以理解为链表的插入排序

start.next = move.next;   

move.next = pre.next  

pre.next = move  

最后,设一个dummy头,这样避免了m=1时没有pre的问题。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        for(int i = 0; i < m - 1; i++) pre = pre.next;
        ListNode start = pre.next;
        ListNode move = null;
        for(int i = 0; i < n - m; i++) {
            move = start.next;
            start.next = move.next;
            move.next = pre.next;
            pre.next = move;
            
        }
        return dummy.next;
    }
}

  

原文地址:https://www.cnblogs.com/Raymond-Yang/p/5207517.html