markruff icon

kotlin - stack

markruff | PRO | 07/23/23 12:05:02 PM UTC | 0 ⭐ | 12675 👁️ | Never ⏰ | [Stack]
Kotlin |

1.03 KB

|

None

|

0 👍

/

0 👎

class Stack<T> {
    
    class Node<T>(v: T) {
        val value: T = v
        var next: Node<T>? = null    
    }
    
    var head: Node<T>? = null
    
    var length: Int = 0
        private set
    
    fun push(v: T) {
        var newNode = Node<T>(v)
        newNode.next = head
        head = newNode
        length++
    }
    
    fun pop(): T? {
        val popper = head ?: return null
        // immutable shadow
        val retval: T = popper.value
        head = popper.next
        length--
        return retval
    }
    
    fun isEmpty(): Boolean = length == 0
    
    fun print() {
        var current: Node<T>? = head
        print ("[")
        while (current != null) {
            print(current.value)
            current = current.next
            if (current != null) print(", ")
        }
        println("]")
    }
    
}
 
fun main() {
    val s: Stack<Int> = Stack<Int>()
    s.push(1)
    s.push(2)
    s.push(3)
    s.print()
    while(s.length > 0)
        println(s.pop())
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎