[leetcode]Reverse Linked List II

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:

类似于[leetcode]Reverse Nodes in k-Group,将m~n区间的节点剪出来,然后reverse之后再插进去。

代码略

思路2:

借鉴了同学的算法,一遍遍历一遍逆序,大致思路是栈操作。

代码如下:

 1 public class Solution {
 2     public ListNode reverseBetween(ListNode head, int m, int n) {
 3         if(head == null || m==n) return head;
 4         ListNode hhead = new ListNode(0);
 5         hhead.next = head;
 6         ListNode pre = hhead;
 7         for(int i = 0 ; i < m - 1; i++){
 8             pre = pre.next;
 9         }
10         ListNode start = pre.next;
11         for(int i = 0; i < n - m; i++){
12             ListNode post = start.next;
13             start.next = post.next;
14             post.next = pre.next;
15             pre.next = post;
16         }
17         return hhead.next;
18     }
19 }

posted on 2014-07-21 21:19  喵星人与汪星人  阅读(182)  评论(0编辑  收藏  举报