★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-vxvyfgoc-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a sorted linked list, delete all duplicates such that each element appear only once.node
Example 1:git
Input: 1->1->2 Output: 1->2
Example 2:github
Input: 1->1->2->3->3 Output: 1->2->3
給定一個排序鏈表,刪除全部重複的元素,使得每一個元素只出現一次。微信
示例 1:app
輸入: 1->1->2 輸出: 1->2
示例 2:spa
輸入: 1->1->2->3->3 輸出: 1->2->3
28ms
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 deleteDuplicates(_ head: ListNode?) -> ListNode? { 14 var temp = head 15 while temp != nil { 16 if temp?.next?.val == temp?.val { 17 temp?.next = temp?.next?.next 18 } else { 19 temp = temp?.next 20 } 21 } 22 23 return head 24 } 25 }
32mscode
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 deleteDuplicates(_ head: ListNode?) -> ListNode? { 14 15 var node: ListNode? = head 16 var next: ListNode? = nil 17 18 while node != nil { 19 20 next = node!.next 21 while next != nil && next!.val == node!.val { 22 next = next!.next 23 } 24 25 node!.next = next 26 node = next 27 } 28 29 return head 30 } 31 }
60mshtm
1 class Solution { 2 func deleteDuplicates(_ head: ListNode?) -> ListNode? { 3 var r = head 4 while r?.next != nil { 5 if r?.val == r?.next?.val { 6 r?.next = r?.next?.next 7 } else { 8 r = r?.next 9 } 10 } 11 return head 12 } 13 }
64msblog
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 14 func deleteDuplicates(_ head: ListNode?) -> ListNode? { 15 guard var head = head else{ 16 return nil 17 } 18 19 func remove(_ current:ListNode, _ previous:ListNode? = nil) { 20 guard let pre = previous else{ 21 if current.next != nil { 22 remove(current.next!,current) 23 } 24 return 25 } 26 if pre.val == current.val { 27 pre.next = current.next 28 if current.next != nil { 29 remove(current.next!,pre) 30 } 31 return 32 }else{ 33 if current.next != nil { 34 remove(current.next!,current) 35 } 36 } 37 } 38 39 remove(head) 40 return head 41 } 42 43 }