Reverse Linked List II

Link:http://oj.leetcode.com/problems/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.

 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       if (head == null || head.next == null)
15             return head;
16         ListNode result = new ListNode(0);
17         result.next = head;
18         head = result;
19         ListNode pre = head, cur = head, post = head;
20         int index = 1;
21 
22         while (index < m) {
23             pre = pre.next;
24             index++;
25         }
26         cur = pre.next;
27         post = cur.next;
28         //in this moment, index = m.
29         //example, for{1,2,3,4}, and m = 1, n = 4,
30         //pre is the "virtual" list node point to 1, and cur point to 1, post points to 2
31         //during the iteration:
32         //2->1->3->4
33         //3->2->1->4
34         //4->3->2->1
35         while (index < n) {
36             index++;
37             //get the next element of post
38             ListNode temp = post.next;
39             //post.next should point to the next element of pre
40             post.next = pre.next;
41             //pre.next should point to the post now
42             pre.next = post;
43             //cur.next will points to the temp, and finally, cur will point to null
44             cur.next = temp;
45             //move post to temp
46             post = temp;
47         }
48         return head.next;
49     }
50 }

 

 

posted on 2014-05-03 05:19  Atlas-Zzz  阅读(271)  评论(0编辑  收藏  举报

导航