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.

first 是第 m -1 个元素。 elementM是第m个元素。 后面将 cur -> second 变成 cur <- second。 最后 cur是第n个元素,second是第n + 1个元素。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode reverseBetween(ListNode head, int m, int n) {
14         // Start typing your Java solution below
15         // DO NOT write main() function
16         ListNode header = new ListNode(-1);
17         header.next = head;
18         ListNode cur = header;
19         ListNode first = null;
20         ListNode elementM = null;
21         ListNode second = null;
22         int i = 0;
23         while(i < m){
24             first = cur;
25             cur = cur.next;
26             i ++;
27         }
28         elementM = cur;
29         second = cur.next;
30         while(i < n){
31             ListNode tmp = second.next;
32             second.next = cur;
33             cur = second;
34             second = tmp;
35             i ++;
36         }
37         first.next = cur;
38         if(elementM != null && elementM != second) elementM.next = second;
39         return header.next;
40     }
41 }

 

第三遍:

 1 public class Solution {
 2     public ListNode reverseBetween(ListNode head, int m, int n) {
 3         ListNode header = new ListNode(-1);
 4         header.next = head;
 5         ListNode first = header, second = header;
 6         for(int i = 1; i < m; i ++){
 7             first = first.next; 
 8         }
 9         ListNode cur = first.next;
10         for(int i = 0; i < n; i ++){
11             second = second.next;
12         }
13         ListNode end = second;
14         second = second.next;
15         end.next = null;
16         while(cur != null){
17             ListNode tmp = cur.next;
18             cur.next = second;
19             second = cur;
20             cur = tmp;
21         }
22         first.next = end;
23         return header.next;
24     }
25 }

 

 

posted on 2013-11-14 17:18  Step-BY-Step  阅读(138)  评论(0编辑  收藏  举报

导航