Leetcode 题目解析之 Reverse Linked List II

2022-01-15 12:06:15 浏览数 (1)

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->NULL, m = 2 and n = 4,

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

Note:

Given m, n satisfy the following condition:

1 ≤ m ≤ n ≤ length of list.]

代码语言:javascript复制
    public ListNode reverseBetween(ListNode head, int m, int n) {

        if (head == null || head.next == null || m == n) {
            return head;
        }

        ListNode fakeHead = new ListNode(-1);
        fakeHead.next = head;

        // 先向后移m步
        ListNode pre = fakeHead;
        for (int i = 1; i < m; i  ) {
            pre = pre.next;
        }

        // 对后面的n-m个结点,逆置
        ListNode mNode = pre.next;
        for (int i = m; i < n; i  ) {
            ListNode cur = mNode.next;
            mNode.next = cur.next;
            cur.next = pre.next;
            pre.next = cur;
        }

        return fakeHead.next;
    }

0 人点赞