Skip to content

Commit 71ee2d5

Browse files
余杜林余杜林
authored andcommitted
添加0203.移除链表元素 Swift版本
1 parent 5850f6d commit 71ee2d5

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

problems/0203.移除链表元素.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,34 @@ var removeElements = function(head, val) {
304304
};
305305
```
306306

307+
Swift:
308+
309+
```swift
310+
/**
311+
* Definition for singly-linked list.
312+
* public class ListNode {
313+
* public var val: Int
314+
* public var next: ListNode?
315+
* public init() { self.val = 0; self.next = nil; }
316+
* public init(_ val: Int) { self.val = val; self.next = nil; }
317+
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
318+
* }
319+
*/
320+
func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
321+
let dummyNode = ListNode()
322+
dummyNode.next = head
323+
var currentNode = dummyNode
324+
while let curNext = currentNode.next {
325+
if curNext.val == val {
326+
currentNode.next = curNext.next
327+
} else {
328+
currentNode = curNext
329+
}
330+
}
331+
return dummyNode.next
332+
}
333+
```
334+
307335

308336

309337

0 commit comments

Comments
 (0)