Swift链接列表删除重复项

时间:2017-07-17 04:45:00

标签: swift data-structures swift3 linked-list

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

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

在方法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))))

1 个答案:

答案 0 :(得分:0)

请查看更新后的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!
}

谢谢