-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathLinkedListStack.swift
74 lines (63 loc) · 1.47 KB
/
LinkedListStack.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//
// LinkedListStack.swift
// Stack
//
// Created by ggl on 2019/4/8.
// Copyright © 2019年 ggl. All rights reserved.
// 链式栈
import Foundation
class LinkedListStack<Element> {
/// 定义链表结点
class Node {
var data: Element
var next: Node?
init(data: Element, next: Node?) {
self.data = data
self.next = next
}
}
/// 底层链表
var head: Node?
/// 元素的个数
var count: Int
init() {
count = 0
}
/// 元素入栈
///
/// - Parameter item: 需要入栈的元素
func push(_ item: Element) {
let node = Node(data: item, next: nil)
if head == nil {
head = node
count = 1
return
}
node.next = head
head = node
count += 1
}
/// 元素出栈
///
/// - Returns: 需要出栈e的元素
@discardableResult
func pop() -> Element? {
if count == 0 {
return nil
}
count -= 1
let item = head!
head = head?.next
return item.data
}
/// 打印元素
func print() {
Swift.print("LinkedListStack元素(靠前的元素表示栈顶元素):", terminator: "")
var item = head
for _ in 0..<count {
Swift.print(item!.data, terminator: " ")
item = item?.next
}
Swift.print("")
}
}