-
Notifications
You must be signed in to change notification settings - Fork 17
/
ReverseLinkedList.java
71 lines (58 loc) · 1.6 KB
/
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
package by.andd3dfx.collections;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* @see <a href="https://youtu.be/iEKdRgKNurg">Video solution</a>
*/
public class ReverseLinkedList {
@Data
@AllArgsConstructor
public static class Node<T> {
private T value;
private Node next;
@Override
public String toString() {
return "Node{v=%s}".formatted(value);
}
}
public static Node reverseUsingLoop(Node head) {
Node prev = null;
Node curr = head;
while (curr != null) {
Node tmp = curr.next;
curr.next = prev;
prev = curr;
curr = tmp;
}
return prev;
}
public static Node reverseUsingStack(Node head) {
Deque<Node> stack = new ArrayDeque<>();
Node curr = head;
while (curr != null) {
stack.push(curr);
curr = curr.next;
}
Node result = stack.peek();
curr = result;
while (!stack.isEmpty()) {
curr.next = stack.pop();
curr = curr.next;
curr.next = null;
}
return result;
}
public static Node reverseUsingRecursion(Node head) {
return recursion(null, head);
}
private static Node recursion(Node prev, Node curr) {
if (curr == null) {
return prev;
}
Node next = curr.next;
curr.next = prev;
return recursion(curr, next);
}
}