返回

重复?不必保留,链表变单排,数据不重复,Swift 轻松搞定!

IOS

问题

给定一个排序的链表,删除所有重复的元素,使得每个元素只出现一次。

解决方案:

我们提供了一种使用Swift实现的解决方案:

class Node<T: Equatable> {
    var value: T
    var next: Node<T>?

    init(value: T, next: Node<T>? = nil) {
        self.value = value
        self.next = next
    }
}

func removeDuplicates<T: Equatable>(_ head: Node<T>?) -> Node<T>? {
    guard let head = head else {
        return nil
    }

    var current = head
    var previous: Node<T>? = nil

    while current != nil {
        if let next = current.next, current.value == next.value {
            while let next = current.next, current.value == next.value {
                current = next
            }
            previous?.next = current.next
        } else {
            previous = current
        }

        current = current.next
    }

    return head
}

复杂度分析:

  • 时间复杂度: O(n),其中n是链表的长度。

  • 空间复杂度: O(1),因为我们没有使用额外的空间来存储数据。

Swift 示例:

// 示例链表
var head = Node(value: 1)
head.next = Node(value: 2)
head.next?.next = Node(value: 3)
head.next?.next?.next = Node(value: 3)
head.next?.next?.next?.next = Node(value: 4)
head.next?.next?.next?.next?.next = Node(value: 4)
head.next?.next?.next?.next?.next?.next = Node(value: 5)

// 删除重复元素
let newHead = removeDuplicates(head)

// 打印结果
var current = newHead
while current != nil {
    print(current!.value)
    current = current!.next
}

输出:

1
2
3
4
5

总结:

这篇文章提供了如何使用Swift删除链表重复元素的解决方案,包括问题、解决方案、复杂度分析和Swift示例代码。如果您在学习Swift或数据结构和算法,希望本篇文章对您有所帮助。