Friday, August 1, 2014

[LeetCode] Reverse Linked 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.

解题思路:
 1. reverse linkedlist,通常需要2个指针和一个temp 指针。这里最后要将reversedlist和原来的list链接起来,所以我们还需要一个指针来存储m-1的node。
2. 这里会考虑到m == 1的情况,所以我们加一个dummy node
 
Java Code:

 public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode p = head;
        ListNode safehead = new ListNode(0);
        safehead.next = head;
        ListNode prevM = safehead;
        ListNode prev = null;
         
        int i = 1;
        
        while( p != null && i <= n){
            if(i >= m){
               ListNode tmp = p;
               p = p.next;
               tmp.next = prev;
               prev = tmp;
            }else{
              prevM = prevM.next;
              p = p.next;
            }
            i++;
        }
       
        prevM.next.next = p;
        prevM.next = prev;
        
        return safehead.next;
    }

No comments:

Post a Comment