2015年9月30日星期三

Leetcode 92 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->NULLm = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Solution 1: simple two pointer problem.
 public class Solution {  
   public ListNode reverseBetween(ListNode head, int m, int n) {  
     ListNode dummy=new ListNode(0);  
     dummy.next=head;  
     ListNode x=dummy, p=dummy, t=dummy;  
     for (int k=0; k<=n; k++) {  
       if (k==m-1) p=x;  
       if (k==n) t=x;  
       x=x.next;  
     }  
     ListNode i=p.next, j=t.next;  
     t.next=null;  
     while (i!=null) {  
       t=i.next;  
       i.next=j;  
       j=i;  
       i=t;  
     }  
     p.next=j;  
     return dummy.next;  
   }  
 }  

没有评论:

发表评论