★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-bsdietxk-md.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Remove all elements from a linked list of integers that have value val.git
Example:github
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5
刪除鏈表中等於給定值 val 的全部節點。微信
示例:spa
輸入: 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 = head 17 while head != nil, head!.val == val { 18 head = head?.next 19 } 20 21 var prev = head 22 var current = head?.next 23 24 while let curr = current { 25 if curr.val == val { 26 prev?.next = curr.next 27 current = curr.next 28 continue 29 } 30 prev = curr 31 current = curr.next 32 } 33 34 return head 35 } 36 }
76mscode
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 : head 17 } 18 }
80mshtm
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 = head 17 var cur = dummy 18 while cur.next != nil { 19 if cur.next!.val == val { 20 cur.next = cur.next!.next 21 } 22 else{ 23 cur = cur.next! 24 } 25 } 26 return dummy.next 27 } 28 }
96msblog
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 nil 17 } 18 19 //在表頭添加一個哨兵節點 20 let fakeNode = ListNode(NSNotFound) 21 fakeNode.next = head 22 var prev:ListNode = fakeNode 23 var current:ListNode? = head 24 while let tmp = current { 25 if tmp.val != val { 26 prev.next = tmp 27 prev = prev.next! 28 } 29 current = tmp.next 30 } 31 32 if prev.next != nil { 33 prev.next = nil 34 } 35 return fakeNode.next 36 } 37 }