首页 > 其他 > 详细

Reverse Linked List II

时间:2015-04-07 11:37:24      阅读:285      评论:0      收藏:0      [点我收藏+]

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.

相关问题是

Reverse Nodes in k-Group

 

 

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode h = new ListNode(-1);
        h.next = head;
        ListNode pre = h;
        int cnt = 1;
        while(cnt<m){
             pre = pre.next;
             cnt++;
        }
        ListNode mnode = pre.next;
        ListNode nnode = mnode;
        while(cnt<n){
            nnode = nnode.next;
            cnt++;
        }
        ListNode end = nnode.next;
        reverse(pre, end);
        return h.next;
    }
    
    public void reverse(ListNode pre, ListNode end){ // B keep to being inserted after pre  pre-1-2-3-end, 1= A, 2=B, 3=t
        ListNode A = pre.next, B  = A.next; // A 定义为B前面一位, 不断的把B塞到pre后面(也就是list的第一位,然后把原来B的前面A链接到B的后面t上去
        while( B!=end){
            ListNode t =  B.next;
            B.next = pre.next;
            pre.next = B;
            A.next = t;
            B=t;
        }
    }
}

 

Reverse Linked List II

原文:http://www.cnblogs.com/jiajiaxingxing/p/4397689.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!