-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathReverseLinkedList.java
More file actions
91 lines (78 loc) · 2.14 KB
/
Copy pathReverseLinkedList.java
File metadata and controls
91 lines (78 loc) · 2.14 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
package by.andd3dfx.collections;
import java.util.ArrayDeque;
import java.util.Deque;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* <pre>
* <a href="https://leetcode.com/problems/reverse-linked-list/">Task description</a>
*
* Given the head of a singly linked list, reverse the list, and return the reversed list.
*
* Example 1:
* <img src="https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg"/>
* Input: head = [1,2,3,4,5]
* Output: [5,4,3,2,1]
*
* Example 2:
* <img src="https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg"/>
* Input: head = [1,2]
* Output: [2,1]
*
* Example 3:
* Input: head = []
* Output: []
* </pre>
*
* @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);
}
}