-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathLinkedListUtils.java
More file actions
53 lines (43 loc) · 1.19 KB
/
LinkedListUtils.java
File metadata and controls
53 lines (43 loc) · 1.19 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
package linklist;
import java.util.Stack;
public class LinkedListUtils {
public static Node reverseRecursive(Node head) {
return swap(head, null);
}
private static Node swap(Node current, Node previous) {
if (current == null) {
return previous;
}
Node right = current.next;
current.next = previous;
return swap(right, current);
}
public static Node reverse(Node head) {
Node current = head;
Node previous = null;
Node next;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}
public static Node reverseUsingStack(Node head) {
Stack<Node> nodes = new Stack<>();
Node current = head;
while (current != null) {
nodes.push(current);
current = current.next;
}
Node newHead = nodes.pop();
current = newHead;
while (!nodes.isEmpty()) {
Node next = nodes.pop();
current.next = next;
current = next;
}
return newHead;
}
}