題目
刪除排序鏈表中的重復元素
問題:
給定一個排序鏈表,刪除所有重復的元素,使得每個元素只出現一次。
示例:
示例 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
}