Reverse Linked List II

来源:互联网 发布:mysql oracle 区别 编辑:程序博客网 时间:2024/05/19 06:38

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.

思路,找到要反转的节点的前一个节点mPre和要反转的节点mNode,将m和n位置处的节点倒置,再将其前后两段连接起来。

/** * 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) {        return null;        }        ListNode mNode = head; // 找到开始反转的节点<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">mNode</span>        ListNode tempHead = new ListNode(0);// 伪头节点        ListNode mPre = tempHead; // 开始发转的节点的前一个节点mPre        tempHead.next = head;        for(int j=1; j<m; j++) {        mPre = mNode;        mNode = mNode.next;        }        ListNode mnext = mNode.next;        ListNode pre;        ListNode p = mNode; // 回溯点       // 反转链表 
<span style="white-space:pre"></span>for(int j=m; j<n; j++) {        pre = mNode;        mNode = mnext;        mnext = mnext.next;        mNode.next = pre;        }        p.next = mnext;        mPre.next = mNode;        head = tempHead.next;return head;    }}



0 0