首页 > 其他 > 详细

Reverse Linked List II

时间:2015-03-14 13:40:51      阅读:228      评论:0      收藏:0      [点我收藏+]

Reverse Linked List II

问题:

Reverse a linked list from position m to n. Do it in-place and in one-pass.

思路:

  三行情书,用的飞起

我的代码:

技术分享
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(m == n)  return head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy; 
        int index = 1;
        while(index < m)
        {
            head = head.next;
            pre = pre.next;
            index++;
        }
        ListNode oldpre = pre;
        while(index <= n)
        {
            if(index == m)
            {
                head = head.next;
                oldpre = oldpre.next;
            }
            else
            {
                oldpre.next = head.next;
                head.next = pre.next;
                pre.next = head;
                head = oldpre.next;
            }
            index++;
        }
        return dummy.next;
    }
}
View Code

 

Reverse Linked List II

原文:http://www.cnblogs.com/sunshisonghit/p/4337411.html

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