-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathreverseSLL_recursive.java
78 lines (66 loc) · 1.94 KB
/
reverseSLL_recursive.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
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
/**
*
* Method 1:
*
* Idea is to reverse the LL after head
* we call reverse function for head.next till tail
* that will reverse the link in that part, let's call that part sub-linked list
*
* that reverse function will return last node of that sub-linked list as its head
* so main challenge would be creating a link b/w head and tail of sub-linked list when we only have access of sub-linked list head
*
* So basically we are recursively reversing the last n-1 nodes
*
* Method 2:
*
* Traverse LL from left to right
* then reverse the first x nodes
* when we are at curr node, we will mark it's prev node as prev, and then we point curr.next to prev
* for next time, curr will be our prev
*/
class Node {
int data;
Node next;
Node(int x)
{
data = x;
next = null;
}
}
public class reverseSLL_recursive {
public static void main(String[] args) {
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
printList(head);
// head = reverseList(head);
head = reverseListtwo(head, null);
printList(head);
}
public static Node reverseList(Node head) {
if (head == null)
return null;
if (head.next == null)
return head;
Node subLLhead = reverseList(head.next);
Node subLLtail = head.next;
subLLtail.next = head;
head.next = null;
return subLLhead;
}
public static Node reverseListtwo(Node curr, Node prev) {
if (curr == null)
return prev;
Node next = curr.next;
curr.next = prev;
return reverseListtwo(next, curr);
}
public static void printList(Node head) {
Node traverse = head;
while (traverse != null) {
System.out.print(traverse.data + "->");
traverse = traverse.next;
}
System.out.print("null\n");
}
}