Skip to content
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit e350f28

Browse files
committed
203. Remove Linked List Elements
1 parent 0757ba3 commit e350f28

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

203. Remove Linked List Elements.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# 203. Remove Linked List Elements
2+
3+
### 2017-03-24
4+
5+
Remove all elements from a linked list of integers that have value **val**.
6+
7+
**Example**
8+
**\*Given:*** 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, **val** = 6
9+
**\*Return:*** 1 --> 2 --> 3 --> 4 --> 5
10+
11+
12+
13+
14+
15+
# Solution
16+
17+
```swift
18+
/**
19+
* Definition for singly-linked list.
20+
* public class ListNode {
21+
* public var val: Int
22+
* public var next: ListNode?
23+
* public init(_ val: Int) {
24+
* self.val = val
25+
* self.next = nil
26+
* }
27+
* }
28+
*/
29+
class Solution {
30+
func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
31+
var newHead: ListNode? = nil
32+
var newTail: ListNode? = nil
33+
var current = head
34+
while let c = current {
35+
if c.val == val {
36+
current = c.next
37+
} else {
38+
if newTail == nil {
39+
newHead = c
40+
newTail = c
41+
} else {
42+
newTail?.next = c
43+
newTail = c
44+
}
45+
current = c.next
46+
newTail?.next = nil
47+
}
48+
49+
}
50+
return newHead
51+
}
52+
}
53+
```
54+

0 commit comments

Comments
 (0)