-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLinkedList.java.off
More file actions
84 lines (78 loc) · 2.24 KB
/
LinkedList.java.off
File metadata and controls
84 lines (78 loc) · 2.24 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
/*
https://leetcode.com/problems/reverse-linked-list/
Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
*/
public class LinkedList {
public static ListNode reverseList(ListNode head) {
if (head == null)
return null;
ListNode cur = head.next;
ListNode prev = head;
head.next = null;
while (cur != null) {
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
public ListNode removeAll(ListNode head, int val) {
ListNode newHead = head;
while (newHead != null && newHead.val == val) {
newHead = newHead.next;
}
if (newHead != null) {
ListNode prev = newHead;
ListNode cur = newHead.next;
while (cur != null) {
ListNode next = cur.next;
if (cur.val == val) {
prev.next = next;
} else {
prev = cur;
}
cur = next;
}
}
return newHead;
}
/*
Remove all val nodes from the list.
Do the first removal check in the same loop as the other checks,
which is less efficient than pre-removing the heads in a separate loop.
*/
public ListNode removeAllOneLoop(ListNode head, int val) {
ListNode prev = null;
ListNode cur = head;
ListNode newHead = head;
while (cur != null) {
ListNode next = cur.next;
if (cur.val == val) {
if (prev == null) {
newHead = next;
} else {
prev.next = next;
}
} else {
prev = cur;
}
cur = next;
}
return newHead;
}
/* Super short, and super inneficient. */
public ListNode removeAllRecursive(ListNode head, int val) {
if(head == null)
return null;
if(head.val == val)
return removeAllRecursive(head.next, val);
head.next = removeAllRecursive(head.next, val);
return head;
}
}