Skip to content

Commit d470682

Browse files
authored
feat: add swift implementation to lcof problem: No.18 (doocs#2877)
1 parent 5fea5a0 commit d470682

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

Diff for: lcof/面试题18. 删除链表的节点/README.md

+33
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,39 @@ public class Solution {
237237
}
238238
```
239239

240+
#### Swift
241+
242+
```swift
243+
/**
244+
* Definition for singly-linked list.
245+
* public class ListNode {
246+
* var val: Int
247+
* var next: ListNode?
248+
* init(_ val: Int, _ next: ListNode? = nil) {
249+
* self.val = val
250+
* self.next = next
251+
* }
252+
* }
253+
*/
254+
255+
class Solution {
256+
func deleteNode(_ head: ListNode?, _ val: Int) -> ListNode? {
257+
let dummy = ListNode(0, head)
258+
var current: ListNode? = dummy
259+
260+
while current?.next != nil {
261+
if current?.next?.val == val {
262+
current?.next = current?.next?.next
263+
break
264+
}
265+
current = current?.next
266+
}
267+
268+
return dummy.next
269+
}
270+
}
271+
```
272+
240273
<!-- tabs:end -->
241274

242275
<!-- solution:end -->
+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* var val: Int
5+
* var next: ListNode?
6+
* init(_ val: Int, _ next: ListNode? = nil) {
7+
* self.val = val
8+
* self.next = next
9+
* }
10+
* }
11+
*/
12+
13+
class Solution {
14+
func deleteNode(_ head: ListNode?, _ val: Int) -> ListNode? {
15+
let dummy = ListNode(0, head)
16+
var current: ListNode? = dummy
17+
18+
while current?.next != nil {
19+
if current?.next?.val == val {
20+
current?.next = current?.next?.next
21+
break
22+
}
23+
current = current?.next
24+
}
25+
26+
return dummy.next
27+
}
28+
}

0 commit comments

Comments
 (0)