algo/kotlin/08_stack/StackBasedOnLinkedList.kt
2019-06-19 01:27:35 +08:00

36 lines
662 B
Kotlin
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 基于链表实现的栈。
*
* Author: Zackratos
*/
class StackBasedOnLinkedList {
private var top: Node? = null
fun push(value: Int) {
val newNode = Node(value, null)
// 不管 top 是不是 null都可以这么写
newNode.next = top
top = newNode
}
fun pop(): Int {
if (top == null) return -1
val node = top
top = top!!.next
return node!!.data
}
fun printAll() {
var p = top
while (p != null) {
print("${p.data} ")
p = p.next
}
println()
}
class Node(var data: Int, var next: Node?)
}