Reverse Linked List II

Problem:s

Reverse a linked list from position m to n.

*Example*
Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL.

Note
Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.

Challenge
Reverse it in-place and in one-pass

Leetcode link
Lintcode link

Solution:

This problem is complex which has many edge cases so that it is not easy to write a bug free program within a short time.
The idea of the solution is to go through the list, to the m, store the previous node before m, and start reversing from m to n.
Then link the non-reversed and reversed part together.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*************************************************************************
> File Name: ReverseLinkedListII.java
> Author: Yao Zhang
> Mail: psyyz10@163.com
> Created Time: Mon 16 Nov 14:48:56 2015
************************************************************************/


public class ReverseLinkedListII{
// Solution 1
public static ListNode reverseBetween(ListNode head, int m, int n) {
if (m>=n) return head;

ListNode current = head;
int i;
ListNode startNode = null, newNode = null, previousNode = null;
for (i = 1; i <= n; i++){
if (i == m - 1){
previousNode = current;
}
if (i == m){
startNode = newNode = current;
}

if (i>m){
ListNode temp = current.next;
current.next = newNode;
newNode = current;
current = temp;
continue;
}

current = current.next;
}

startNode.next = current;

if (previousNode == null) head = newNode;
else previousNode.next = newNode;

return head;
}

// Solution 2
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m >= n || head == null)
return head;

ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode prev = dummy;

for (int i = 0; i < m - 1 ; i++){
if (prev == null) {
return dummy.next;
}
prev = prev.next;
}

ListNode mPrev = prev;
ListNode current = prev.next;
ListNode last = new ListNode(current.val);
ListNode first = last;
current = current.next;

for (int i = 0; i < n - m ; i++){
if (current == null) {
return dummy.next;
}
ListNode temp = current.next;
current.next = first;
first = current;
current = temp;
}

mPrev.next = first;

last.next = current;

return dummy.next;
}
}