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

 

你可能感兴趣的:(list)