-
Notifications
You must be signed in to change notification settings - Fork 13
/
LL_ReverseLinkedList.java
76 lines (63 loc) · 2 KB
/
LL_ReverseLinkedList.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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
// https://www.geeksforgeeks.org/reverse-a-linked-list/
// https://practice.geeksforgeeks.org/problems/reverse-a-linked-list/1
class LL_ReverseLinkedList {
private static Node reverseLinkedList(Node head) {
Node prev = null;
Node curr = head;
Node next = null;
while(curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
while (t-->0) {
int n = Integer.parseInt(br.readLine().trim());
String str[] = br.readLine().trim().split("\\s+");
int ip[] = new int[n];
for (int i = 0; i < n; i++) {
ip[i] = Integer.parseInt(str[i]);
}
Node head = buildLinkedList(ip);
printLinkedList(head);
Node reversedHead = reverseLinkedList(head);
printLinkedList(reversedHead);
}
}
private static Node buildLinkedList(int[] ip) {
Node head = new Node(ip[0]);
Node tail = head;
for (int i = 1; i < ip.length; i++) {
tail.next = new Node(ip[i]);
tail = tail.next;
}
return head;
}
private static void printLinkedList(Node head) {
StringBuffer sb = new StringBuffer();
Node temp = head;
while(temp != null) {
sb.append(temp.value + " ");
temp = temp.next;
}
System.out.println(sb);
sb.setLength(0);
}
private static final class Node {
private int value;
private Node next;
Node(int value) {
this.value = value;
this.next = null;
}
}
}