Skip to content

Latest commit

 

History

History
35 lines (35 loc) · 1.09 KB

92.md

File metadata and controls

35 lines (35 loc) · 1.09 KB

#92. Reverse Linked List II 题目链接

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (m == n) {
            return head;
        }
        ListNode beforeHead = new ListNode(0);
        /*
            设置beforeHead原因是,因为head结点是第一个结点,如果交换从第一个结点就开始的话,
            head结点会变化,就不再是第一个结点了,所以设值一个变量,让它的next指向第一个结点
         */
        beforeHead.next = head;
        ListNode pre = beforeHead;
        for(int i = 0; i < m - 1; i++) {
            pre = pre.next;
        }
        ListNode start = pre.next;
        ListNode then = start.next;
        /*
            1->2->3->4 m=2 n=4
         ==>1->3->2->4
         ==>1->4->3->2
         */
        for(int i = 0; i < n - m; i++) {
            start.next = then.next;
            then.next = pre.next;
            pre.next = then;
            then = start.next;
        }
        return beforeHead.next;
    }
}