节点
class ListNode<T> {
var value: T
var next: ListNode?
public init(value: T, next: ListNode? = nil) {
self.value = value
self.next = next
}
}
扩展描述
extension ListNode: CustomStringConvertible {
var description: String {
guard let next = next else {
return "\(value)"
}
return "\(value)" + "\(String(describing: next))"
}
}
链表实现
class LinkedSingleList<T> {
var head: ListNode<T>?
var tail: ListNode<T>?
var isEmpty: Bool {
return head == nil
}
// 相当于压栈, 后面的元素放到最上(前)面
func push(_ value: T) {
head = ListNode(value: value, next: head)
if tail == nil {
tail = head
}
}
// 出栈
@discardableResult
func pop() -> T? {
trackTailNode()
defer {
head = head?.next
if isEmpty {
tail = nil
}
}
return head?.value
}
// 尾部追加
func append(_ value: T) {
trackTailNode()
guard !isEmpty else {
push(value)
return
}
tail?.next = ListNode(value: value)
// 别忘记尾部指针后移
tail = tail?.next
}
// 根据索引找到相关节点
@discardableResult
func node(at index: Int) -> ListNode<T>? {
var currentIndex = 0
var currentNode: ListNode<T>?
while currentNode != nil && currentIndex < index {
currentIndex += 1;
currentNode = currentNode?.next
}
return currentNode
}
// 删除最后一个节点
@discardableResult
func removeLast() -> T? {
guard let head = head, head.next != nil else {
return pop()
}
var prev = head
var current = head
while let next = current.next {
prev = current
current = next
}
prev.next = nil
tail = prev
return current.value
}
// 删除指定索引的节点
@discardableResult
func remove(at index: Int) -> T? {
guard let head = head, head.next != nil else {
return pop()
}
var prev = head
var current = head
var currentIndex = 0
while let next = current.next, currentIndex <= index {
prev = current
current = next
currentIndex += 1
}
prev.next = current.next
return current.value
}
// 删除指定节点后的节点
@discardableResult
func remove(after node: ListNode<T>) -> T? {
trackTailNode()
defer {
if tail === node.next {
tail = node
}
node.next = node.next?.next
}
return node.next?.value
}
// 反转
func reverse() {
var prev = head
var current = head?.next
// 头部变尾部
tail = head
// 最后一个节点没有next
tail?.next = nil
while current != nil { // 直到 current 为 nil
let next = current?.next // 获取下一个节点
current?.next = prev // 重新设置下一个节点
prev = current // 向前移动
current = next // 向后移动
}
head = prev
}
// 找到尾部
func trackTailNode() {
guard !isKnownUniquelyReferenced(&head) else { return }
guard var oldNode = head else { return }
// 重置 head
head = ListNode(value: oldNode.value)
// 初始化变量
var newNode = head
// 遍历直到找到尾部节点
while let nextOldNode = oldNode.next {
newNode?.next = ListNode(value: nextOldNode.value)
newNode = newNode?.next
oldNode = nextOldNode
}
tail = newNode
}
// 打印
func printInReverse<T>(_ node: ListNode<T>?) {
guard let node = node else { return }
printInReverse(node.next)
print(node.value)
}
}
网友评论