Remove all elements from a linked List of integers that have value val.
Example:
input: 1->2->6->3->4->5->6,val = 6Output: 1->2->3->4->5
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6,val = 6输出: 1->2->3->4->5
72ms
1 /** 2 * DeFinition for singly-linked List. 3 * public class ListNode { 4 * public var val: Int 5 * public var next: ListNode? 6 * public init(_ val: Int) { 7 * self.val = val 8 * self.next = nil 9 * }10 * }11 */12 class Solution {13 func removeElements(_ head: ListNode?,_ val: Int) -> ListNode? {14 guard head != nil else { return nil }15 16 var head = head17 while head != nil,head!.val == val {18 head = head?.next19 }20 21 var prev = head22 var current = head?.next23 24 while let curr = current {25 if curr.val == val {26 prev?.next = curr.next27 current = curr.next28 continue29 }30 prev = curr31 current = curr.next32 }33 34 return head35 }36 }
76ms
1 /** 2 * DeFinition for singly-linked List. 3 * public class ListNode { 4 * public var val: Int 5 * public var next: ListNode? 6 * public init(_ val: Int) { 7 * self.val = val 8 * self.next = nil 9 * }10 * }11 */12 class Solution {13 func removeElements(_ head: ListNode?,_ val: Int) -> ListNode? {14 guard let head = head else { return nil }15 head.next = removeElements(head.next,val)16 return head.val == val ? head.next : head17 }18 }
80ms
1 /** 2 * DeFinition for singly-linked List. 3 * public class ListNode { 4 * public var val: Int 5 * public var next: ListNode? 6 * public init(_ val: Int) { 7 * self.val = val 8 * self.next = nil 9 * }10 * }11 */12 class Solution {13 func removeElements(_ head: ListNode?,_ val: Int) -> ListNode? {14 15 var dummy = ListNode(-1)16 dummy.next = head17 var cur = dummy18 while cur.next != nil {19 if cur.next!.val == val {20 cur.next = cur.next!.next21 }22 else{23 cur = cur.next!24 }25 }26 return dummy.next27 }28 }
96ms
1 /** 2 * DeFinition for singly-linked List. 3 * public class ListNode { 4 * public var val: Int 5 * public var next: ListNode? 6 * public init(_ val: Int) { 7 * self.val = val 8 * self.next = nil 9 * }10 * }11 */12 13 class Solution {14 func removeElements(_ head: ListNode?,_ val: Int) -> ListNode? {15 guard let _ = head else {16 return nil17 }18 19 //在表头添加一个哨兵节点20 let fakeNode = ListNode(NSNotFound)21 fakeNode.next = head22 var prev:ListNode = fakeNode23 var current:ListNode? = head24 while let tmp = current {25 if tmp.val != val {26 prev.next = tmp27 prev = prev.next!28 }29 current = tmp.next30 }31 32 if prev.next != nil {33 prev.next = nil34 }35 return fakeNode.next36 }37 }@H_404_2@ 总结
以上是内存溢出为你收集整理的[Swift]LeetCode203. 移除链表元素 | Remove Linked List Elements全部内容,希望文章能够帮你解决[Swift]LeetCode203. 移除链表元素 | Remove Linked List Elements所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)