-
-
Notifications
You must be signed in to change notification settings - Fork 611
/
ReverseLinkedList.java
52 lines (42 loc) · 1.22 KB
/
ReverseLinkedList.java
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
package problems.easy;
import problems.utils.ListNode;
/**
* Created by sherxon on 1/4/17.
*/
public class ReverseLinkedList {
/**
* This is recursive solution
*/
ListNode newHead;
/**
* Case: Reverse Linked list in one pass without extra space.
* This can be solved recursively and iteratively. Iterative solution is given below.
* We get each node in iteration and set previous node of this node as next node.
*Time complexity is O(N)
* */
public ListNode reverseList(ListNode root) {
ListNode newHead = null;
while (root != null) {
ListNode nextNode = root.next;
root.next = newHead;
newHead = root;
root = nextNode;
}
return newHead;
}
public ListNode reverseList2(ListNode head) {
if (head == null || head.next == null) return head;
reverse(head);
head.next = null;
return newHead;
}
ListNode reverse(ListNode current) {
if (current == null || current.next == null) {
newHead = current;
return current;
}
ListNode prev = reverse(current.next);
prev.next = current;
return current;
}
}