LeetCode(92):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.

For example:Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:

Given m, n satisfy the following condition:

1 ≤ mn ≤ length of list.

题意:反转链表,反转指定位置的链表。

思路:参考这里,主要是先找到要反转链表的开始反转的结点,然后一个个的反转,最后和其两边的部分进行连接。

代码:

public ListNode reverseBetween(ListNode head, int m, int n) {
         if(head==null) return null;
         ListNode q = null;
         ListNode p = head;
         for(int i=0;i<m-1;i++){
             q = p;
             p = p.next;
         }
         ListNode end = p;
         ListNode pPre = p;
         p = p.next;
         for(int i=m+1;i<=n;i++){
             ListNode pNext = p.next;
             p.next = pPre;
             pPre = p;
             p = pNext;
         }
         end.next = p;
         if(q!=null)
            q.next = pPre;
        else
            head = pPre;
        return head;
    }
posted @ 2016-01-18 19:01  Lewisr  阅读(125)  评论(0编辑  收藏  举报