Swift - LeetCode - 刪除排序連結串列中的重複元素
題目
刪除排序連結串列中的重複元素
問題:
給定一個排序連結串列,刪除所有重複的元素,使得每個元素只出現一次。
示例:
示例 1: 輸入: 1->1->2 輸出: 1->2 示例 2: 輸入: 1->1->2->3->3 輸出: 1->2->3
解題思路:
移除有序連結串列中的重複項需要定義個指標指向該連結串列的第一個元素,然後第一個元素和第二個元素比較,如果重複了,則刪掉第二個元素,如果不重複,指標指向第二個元素。這樣遍歷完整個連結串列,則剩下的元素沒有重複項。
程式碼:
/** public class SingNode { public var value : Int public var nextNode: SingNode? public init(value:Int) { self.value = value } } extension SingNode : CustomStringConvertible { public var description: String { var string = "\(value)" var node = self.nextNode while node != nil { string = string + " -- " + "\(node!.value)" node = node?.nextNode } return string } } **/ func removeSameNode(_ l1 : SingNode?) -> SingNode? { if l1 == nil || l1?.nextNode == nil { return l1 } var tempNode = l1 while tempNode != nil && tempNode?.nextNode != nil { if tempNode?.value == tempNode?.nextNode?.value { let nextNode = tempNode?.nextNode tempNode?.nextNode = nextNode?.nextNode } tempNode = tempNode?.nextNode } return l1 }