-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinked_List_02.java
More file actions
101 lines (78 loc) · 2.12 KB
/
Copy pathLinked_List_02.java
File metadata and controls
101 lines (78 loc) · 2.12 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Reverse a linked list
class Node{
int val;
Node next;
Node(int data){
this.val=data;
this.next=null;
}
}
class Linked_List{
Node head;
public void Add(int data){
Node new_Node=new Node(data);
if(head==null){
head=new_Node;
return;
}
Node curr=head;
while(curr.next!=null){
curr=curr.next;
}
curr.next=new_Node;
return;
}
public void Reverse_LL_Iterative(){
Node prev=head;
Node curr=head.next;
while(curr!=null){
Node next=curr.next;
curr.next=prev;
prev=curr;
curr=next;
}
head.next=null;
head=prev;
}
// Recursive Method
public Node Reverse_LL_Recursive(Node head) {
// 1. Base case: if head is null or we reach the last node
if (head == null || head.next == null) {
return head;
}
// 2. Recursively reverse the rest of the list
// newHead will eventually hold the very last node (which becomes the new first node)
Node newHead = Reverse_LL_Recursive(head.next);
// 3. Reverse the pointer of the next node to point back to the current node
head.next.next = head;
// 4. Break the forward pointer of the current node to prevent cycles
head.next = null;
// 5. Return the new head up the call stack
return newHead;
}
public void Print_LL(){
Node curr=head;
while(curr!=null){
System.out.print(curr.val + " -> ");
curr=curr.next;
}
System.out.print("Null");
System.out.println();
}
}
public class Linked_List_02 {
public static void main(String[] args){
Linked_List list=new Linked_List();
list.Add(0);
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
list.Print_LL();
list.Reverse_LL_Iterative();
list.Print_LL();
list.head=list.Reverse_LL_Recursive(list.head);
list.Print_LL();
}
}