Implementing a generic linked list in Swift allows for a flexible data structure that can hold any data type. Below is an example of how to create a simple generic linked list.
class Node {
var value: T
var next: Node?
init(value: T) {
self.value = value
self.next = nil
}
}
class LinkedList {
private var head: Node?
private var tail: Node?
private var count: Int = 0
var isEmpty: Bool {
return head == nil
}
var size: Int {
return count
}
func append(value: T) {
let newNode = Node(value: value)
if let tailNode = tail {
tailNode.next = newNode
} else {
head = newNode
}
tail = newNode
count += 1
}
func printList() {
var currentNode = head
while let node = currentNode {
print(node.value, terminator: " -> ")
currentNode = node.next
}
print("nil")
}
}
let list = LinkedList()
list.append(value: 1)
list.append(value: 2)
list.append(value: 3)
list.printList() // Output: 1 -> 2 -> 3 -> nil
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?