LeetCode92. Reverse Linked List ii

来源:互联网 发布:京麦工作台和淘宝助理 编辑:程序博客网 时间:2024/05/22 01:23

description:
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.

解题思路:
首先找到一个m的前驱节点和n的后继节点。
然后建立一个front的前指针,每次后面的数字移动到front之前,然后更新front的指向。
最后将list连接起来。

/** * 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) {        if (head == null || m > n)  {            return null;        }          ListNode dummy = new ListNode(0);        dummy.next = head;        head = dummy;        for (int i = 0; i < m - 1; i++) {            if (head == null) {                return null;            }            head = head.next;        }        ListNode preNode = head;        ListNode mNode = head.next;        ListNode nNode = mNode;        ListNode postNode = mNode.next;        for (int i = m; i < n; i++) {            if (postNode == null) {                return null;            }            ListNode temp = postNode.next;            postNode.next = nNode;            nNode = postNode;            postNode = temp;        }        preNode.next = nNode;        mNode.next = postNode;        return dummy.next;    }}
0 0
原创粉丝点击