快速链表删除重复项



我在下面编写了程序来从链表中删除重复项,

下面是包含节点类和通过遍历链表删除重复项的方法的代码。

在方法removeDuplicates中,但是当我在检查时执行时失败( cur != nil ),当更改为cur.link != nil时将起作用,但输出不正确。

import UIKit
class LinkedList {
class Node {
var data:Int
var link: Node?
init(data: Int = 0 ){
self.data = data
self.link = nil
}
}
func disp(n: Node?) -> String{
var text = String()
var node = n
while node != nil{
text += "(node!.data)"
node = node?.link
if node != nil {
text += "--->"
}
}
return text
}
func removeDuplicatesNode( head : Node?) -> Node?{
var cur = head
var prev:Node? = nil
let s = NSMutableSet()
while ( cur != nil ) {
let val:Int = cur!.data
if( s.contains(val)){
prev?.link = cur?.link!
}else{
s.add(val)
prev = cur
}
print(cur)
cur = cur?.link
}
return head!
}
}
var list = LinkedList()
var removeDuplicates = LinkedList.Node(data: 1)
removeDuplicates.link = LinkedList.Node(data: 2)
removeDuplicates.link?.link = LinkedList.Node(data: 3)
removeDuplicates.link?.link?.link = LinkedList.Node(data: 3)
print("Remove Duplicates " + list.disp(n: (list.removeDuplicatesNode(head: removeDuplicates))))

请查看更新的 removeDuplicateNode(( 函数。我用 nil 条件更新了代码。

func removeDuplicatesNode( head : Node?) -> Node?{
var cur = head
var prev:Node? = nil
let s = NSMutableSet()
while ( cur != nil ) {
let val:Int = cur!.data
if( s.contains(val)){
if cur?.link != nil { // Check for last Node
prev?.link = cur?.link!
}else{
prev?.link = nil // If last node then assign nil value to the prev node's link
}
}else{
s.add(val)
prev = cur
}
print(cur!)
cur = cur?.link
}
return head!
}

谢谢

相关内容

  • 没有找到相关文章

最新更新