Reverse Linked List II

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

 

posted on 2015-03-14 13:27  zhouzhou0615  阅读(147)  评论(0编辑  收藏  举报

导航