-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_ll.java
79 lines (62 loc) · 1.49 KB
/
reverse_ll.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
79
public class ReverseLL {
public static Node<Integer> reverseR(Node<Integer> head){
if(head == null || head.next == null){
return head;
}
Node<Integer> finalHead = reverseR(head.next);
Node<Integer> temp = finalHead;
while(temp.next != null){
temp = temp.next;
}
temp.next = head;
head.next = null;
return finalHead;
}
//optimize
public static Node<Integer> reverseR(Node<Integer> head){
if(head == null || head.next == null){
return head;
}
Node<Integer> reversedTail = head.next;
Node<Integer> smallHead = reverseR(head.next);
reversedTail.next = head;
head.next = null;
return smallHead;
}
public static Node<Integer> takeInput()
{
Node<Integer> head = null, tail = null;
Scanner s = new Scanner(System.in);
int data = s.nextInt();
while(data != -1){
Node<Integer> newNode = new Node<Integer>(data);
if(head == null){
head = newNode;
tail = newNode;
}else{
// Node<Integer> temp = head;
// while(temp.next != null){
// temp = temp.next;
// }
// temp.next = newNode;
tail.next = newNode;
tail = newNode; // tail = tail.next
}
data = s.nextInt();
}
return head;
}
public static void print(Node<Integer> head){
while(head != null){
System.out.print(head.data +" ");
head = head.next;
}
System.out.println();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Node<Integer> head = takeInput();
head = reverseR(head);
print(head);
}
}