Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 53952ae

Browse files
LC#203 remove given value from linked list,iterative and recursive solution
1 parent 3da6417 commit 53952ae

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package LinkedList;
2+
3+
public class RemoveLinkedListElement203 {
4+
5+
public class ListNode {
6+
int val;
7+
ListNode next;
8+
9+
ListNode() {
10+
}
11+
12+
ListNode(int val) {
13+
this.val = val;
14+
}
15+
16+
ListNode(int val, ListNode next) {
17+
this.val = val;
18+
this.next = next;
19+
}
20+
}
21+
22+
// O(N) time, O(1) space
23+
public ListNode removeElements(ListNode head, int val) {
24+
25+
if (head == null)
26+
if (head == null)
27+
return null;
28+
29+
ListNode dummy = new ListNode(-1);
30+
dummy.next = head;
31+
ListNode tail = dummy;
32+
33+
while (head != null) {
34+
if (head.val == val) {
35+
ListNode temp = head.next;
36+
tail.next = temp;
37+
head = temp;
38+
} else {
39+
head = head.next;
40+
tail = tail.next;
41+
}
42+
}
43+
44+
return dummy.next;
45+
}
46+
47+
// recursive approach
48+
public ListNode removeElementsRecursive(ListNode head, int val) {
49+
50+
if (head == null)
51+
return null;
52+
53+
head.next = removeElementsRecursive(head.next, val);
54+
55+
// can also write it using ternary operator
56+
if (head.val == val) {
57+
return head.next;
58+
} else
59+
return head;
60+
}
61+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /