leetcode--Reverse Linked List II

来源:互联网 发布:understand mac 破解 编辑:程序博客网 时间:2024/06/03 17:57

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.

[java] view plain copy
  1. /** 
  2.  * Definition for singly-linked list. 
  3.  * public class ListNode { 
  4.  *     int val; 
  5.  *     ListNode next; 
  6.  *     ListNode(int x) { val = x; } 
  7.  * } 
  8.  */  
  9. public class Solution {  
  10.     public ListNode reverseBetween(ListNode head, int m, int n) {  
  11.         if(n==m) return head;  
  12.         if(m>n){  
  13.             int t = n;  
  14.             n = m;  
  15.             m = t;  
  16.         }  
  17.         ListNode h = head;        
  18.         ListNode res = new ListNode(-1);  
  19.         ListNode pre = res;  
  20.         pre.next = h;  
  21.         int count = 1;        
  22.         //pre为m前的值  
  23.         while(h!=null&&count<m){  
  24.             pre = pre.next;  
  25.             h = h.next;  
  26.             count++;  
  27.         }     
  28.         ListNode cur = h;//找到m对应的值        
  29.         ListNode fhead = new ListNode(-1);  
  30.         ListNode last = cur;//第一个,然后会成为最后一个  
  31.         while(count<=n){  
  32.             pre.next = cur.next;  
  33.             cur.next = fhead.next;  
  34.             fhead.next = cur;  
  35.             cur = pre.next;  
  36.             count++;  
  37.         }         
  38.         last.next = pre.next;  
  39.         pre.next = fhead.next;  
  40.         return res.next;  
  41.     }  
  42. }  


原文链接http://blog.csdn.net/crazy__chen/article/details/46444071

原创粉丝点击