Skip to content

Instantly share code, notes, and snippets.

@YuanLiou
Created December 1, 2017 14:37
Show Gist options
  • Select an option

  • Save YuanLiou/efc31f78f0cc6365489d033df7b8ea97 to your computer and use it in GitHub Desktop.

Select an option

Save YuanLiou/efc31f78f0cc6365489d033df7b8ea97 to your computer and use it in GitHub Desktop.
Stack in Kotlin
class Node {
internal var text: String = ""
internal var nextNode: Node? = null
}
class Stack {
var head: Node? = null
fun pop(): String? {
val result: String? = head?.text
head = head?.nextNode
return result
}
fun push(value: String) {
val newNode = Node()
newNode.text = value
newNode.nextNode = head
head = newNode
}
fun size(): Int {
var size = 0
var node = head
while (node != null) {
size++
node = node.nextNode
}
return size
}
fun isEmpty(): Boolean {
return head == null
}
}
fun main(args: Array<String>) {
val stack = Stack()
checkSize(stack)
// add something
stack.push("Nick")
// checkSize(stack)
// pop something
// stack.pop()
// checkSize(stack)
stack.push("Sue")
stack.push("Eric")
stack.push("David")
checkSize(stack)
for (i in stack.size() downTo 1) {
println("pop result = " + stack.pop())
}
}
fun checkSize(stack: Stack) {
println("isEmpty? = " + stack.isEmpty())
println("size = " + stack.size())
println("")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment