首页 > 其他 > 详细

Reverse Linked List II

时间:2014-02-17 16:46:49      阅读:366      评论:0      收藏:0      [点我收藏+]

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.

bubuko.com,布布扣
 1 public class Solution {
 2     public ListNode reverseBetween(ListNode head, int m, int n) {
 3         if(head==null || m==n) return head;
 4         ListNode safe = new ListNode(-1);
 5         ListNode pre = safe;
 6         safe.next = head;
 7         int step = n-m;
 8         while(m>1){
 9             pre = pre.next;//to the previous of m_th node
10             m--;
11         }
12         ListNode cur = pre.next;
13         ListNode post = cur.next;
14         while(step>0 ){
15             ListNode temp = post.next;
16             post.next = cur;
17             cur = post;
18             post = temp;
19             step--;
20         }
21         ListNode temp = pre.next;
22         pre.next = cur;
23         temp.next = post;
24         return safe.next;
25     }
26 }
View Code

Reverse Linked List II

原文:http://www.cnblogs.com/krunning/p/3552035.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!