Swift链表删除重复项

Swift链表删除重复项,swift,data-structures,swift3,linked-list,Swift,Data Structures,Swift3,Linked List,我写了下面的程序来删除链表中的重复项 下面是代码,其中包含通过遍历链表来删除重复项的节点类和方法 在方法RemovedUpplicates中,当我执行cur时,它会失败!=无检查,当更改为cur.link!=nil将工作,但输出不正确 import UIKit class LinkedList { class Node { var data:Int var link: Node? init(data: Int = 0 ){

我写了下面的程序来删除链表中的重复项

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

在方法RemovedUpplicates中,当我执行cur时,它会失败!=无检查,当更改为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))))

请查看更新的RemovedUpplicateNode函数。我用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!
}

谢谢

请查看更新的RemovedUpplicateNode功能。我用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!
}
多谢各位