forked from rituburman/hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseLinkedList.java
More file actions
140 lines (115 loc) · 2.69 KB
/
ReverseLinkedList.java
File metadata and controls
140 lines (115 loc) · 2.69 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
130
131
132
133
134
135
136
137
138
import java.util.*;
import java.io.*;
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
public class ReverseLL
{
Node head; // head of lisl
Node lastNode;
static PrintWriter out;
/* Linked list Node*/
/* Utility functions */
/* Inserts a new Node at front of the list. */
public void addToTheLast(Node node)
{
if (head == null)
{
head = node;
lastNode = node;
}
else
{
Node temp = head;
lastNode.next = node;
lastNode = node;
}
}
/* Function to print linked list */
void printList()
{
Node temp = head;
while (temp != null)
{
out.print(temp.data+" ");
temp = temp.next;
}
out.println();
}
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedOutputStream(System.out));
int t= Integer.parseInt(br.readLine());
while(t>0)
{
int n = Integer.parseInt(br.readLine());
ReverseLL rll = new ReverseLL();
String nums[] = br.readLine().split(" ");
if (n > 0)
{
int a1= Integer.parseInt(nums[0]);
Node head= new Node(a1);
rll.addToTheLast(head);
}
for (int i = 1; i < n; i++)
{
int a = Integer.parseInt(nums[i]);
rll.addToTheLast(new Node(a));
}
rll.head = new ReverseLL().reverseList(rll.head);
rll.printList();
t--;
}
out.close();
}
}
// } Driver Code Ends
//function Template for Java
/* Return reference of new head of the reverse linked list
class Node {
int value;
Node next;
Node(int value) {
this.value = value;
}
} */
class ReverseLL
{
// This function should reverse linked list and return
// head of the modified linked list.
Node reverseList(Node head)
{
if(head==null)
{
return null;
}
if(head.next==null)
{
return head;
}
Stack<Integer> s = new Stack<>();
Node temp=head;
while(temp.next!=null)
{
s.push(temp.data);
temp=temp.next;
}
s.push(temp.data);
temp = head;
while(temp.next!=null)
{
temp.data= s.pop();
temp=temp.next;
}
temp.data=s.pop();
return head;
}
}