码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Linked List II

时间:2015-04-12 06:32:42      阅读:189      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!