From 71ee2d5d0bc9dba8f2d83156c05ea17a5353036a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BD=99=E6=9D=9C=E6=9E=97?= Date: Sun, 15 Aug 2021 21:35:27 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00203.=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0203.移除链表元素.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index a2c6e90d..9235d47e 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -304,6 +304,34 @@ var removeElements = function(head, val) { }; ``` +Swift: + +```swift +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? { + let dummyNode = ListNode() + dummyNode.next = head + var currentNode = dummyNode + while let curNext = currentNode.next { + if curNext.val == val { + currentNode.next = curNext.next + } else { + currentNode = curNext + } + } + return dummyNode.next +} +``` +