首页 > 其他 > 详细

Reverse Linked List II

时间:2015-04-12 06:31:15      阅读:166      评论: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.

 1     public ListNode reverseBetween(ListNode head, int m, int n) {
 2         if(head == null) return null;
 3         ListNode dummy = new ListNode(0);
 4         dummy.next = head;
 5         ListNode pre = dummy;
 6         ListNode start = head;
 7         
 8         for (int i = 1; i < m; i++) {
 9             start = start.next;
10             pre = pre.next;
11         }
12         ListNode end = start;
13         ListNode then = start.next;
14         ListNode temp = then;
15         for (int j = 0; j < n - m;  j++) {
16             temp = then.next;
17             then.next = start;
18             start = then;
19             then = temp;
20         }
21         pre.next = start;
22         end.next = then;
23         return dummy.next;
24     }

感觉写的挺丑的。。。

Reverse Linked List II

原文:http://www.cnblogs.com/gonuts/p/4418880.html

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