-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseLinkedListRecursion.java
More file actions
129 lines (87 loc) · 2.83 KB
/
ReverseLinkedListRecursion.java
File metadata and controls
129 lines (87 loc) · 2.83 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*package whatever //do not write package name here */
import java.io.*;
class DoublyLinkedListNode{
private int data;
private DoublyLinkedListNode prev;
private DoublyLinkedListNode next;
public DoublyLinkedListNode(int data){
this.data = data;
this.prev = null;
this.next = null;
}
public void setNext(DoublyLinkedListNode node){
this.next = node;
}
public void setPrev(DoublyLinkedListNode node){
this.prev = node;
}
public DoublyLinkedListNode getNext(){
return this.next;
}
public DoublyLinkedListNode getPrev(){
return this.prev;
}
public int getData(){
return this.data;
}
}
public class ReverseLinkedListRecursion {
public DoublyLinkedListNode head, tail;
public ReverseLinkedListRecursion(){
head = null;
tail = null;
}
public void insert(int data){
DoublyLinkedListNode node = new DoublyLinkedListNode(data);
if(head == null){
System.out.println("yes here for " + data);
head = tail = node;
}
else{
node.setPrev(tail);
tail.setNext(node);
tail = node;
}
}
//method to reverse Linkedlist using technique of recursion and changing pointer of a node one at a time.
public DoublyLinkedListNode reverse(DoublyLinkedListNode node1){
if(node1 == null){
return null;
}
DoublyLinkedListNode node = node1; //store the address of the current node
DoublyLinkedListNode temp = reverse(node1.getNext()); // recursion call till it reaches last node and then traverses back up.
node.setNext(node.getPrev());
node.setPrev(temp);
if(node.getPrev() == null){
head = node; // the head node will be the last node now
}
if(node.getNext() == null){
tail = node;
}
return node;
}
public DoublyLinkedListNode print(DoublyLinkedListNode node){
if(node == null){
return null;
}
System.out.print(node.getData());
if(node.getNext() != null){
System.out.print("->");
}
node = node.getNext();
print(node);
return node;
}
public static void main (String[] args) {
ReverseLinkedListRecursion ll = new ReverseLinkedListRecursion();
ll.insert(10);
ll.insert(20);
ll.insert(30);
ll.insert(40);
System.out.println(ll.head.getData());
ll.print(ll.head);
ll.reverse(ll.head);
System.out.println();
ll.print(ll.head);
}
}