Created
December 1, 2017 14:37
-
-
Save YuanLiou/efc31f78f0cc6365489d033df7b8ea97 to your computer and use it in GitHub Desktop.
Stack in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Node { | |
| internal var text: String = "" | |
| internal var nextNode: Node? = null | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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