`

Leetcode - Reversed Linked ListII

    博客分类:
  • List
 
阅读更多

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) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(m == n)
            return head;
            
        ListNode pBefore = new ListNode(-1);
        pBefore.next = head;
        ListNode prev, curr = head,next;
        
        int c = 1;
        while(c < m){
            pBefore = pBefore.next;
            c++;
        }
        
        ListNode mNode = pBefore.next;
        prev = pBefore.next;
        curr = prev.next;
        while(c < n){
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
            c++;
        }
        pBefore.next = prev;
        mNode.next = curr;
        
        return mNode == head ? pBefore.next : head;
    }

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics