class Stack: NSObject {
var count: Int = 0
private var array: [Any] = [Any]()
func push(element: Any) -> Bool {
self.array.append(element)
count += 1
return true
}
func pop() -> Any? {
if count == 0 {
return nil
}
let element = self.array.removeLast()
count -= 1
return element
}
}
class LinkStack: NSObject {
var count: Int = 0
private var headNode: Node = Node()
override init() {
self.headNode.next = nil
self.headNode.data = nil
}
func push(element: Any) -> Bool {
let node = Node()
node.data = element
if count == 0 {
self.headNode.next = node
node.next = nil
count += 1
return true
}
node.next = self.headNode.next
self.headNode.next = node
count += 1
return true
}
func pop() -> Any? {
var node = self.headNode.next
if node == nil {
return nil
}
if count == 1{
self.headNode.next = nil
count = 0
return node
}
//找到尾结点的前一个结点
while count > 1 && node?.next?.next != nil {
node = node?.next
}
let popNode = node?.next
node?.next = nil
count -= 1
return popNode
}
}
class Node {
var data: Any?
var next: Node?
}