MaximilianH
05/25/2025, 6:39 AMclass Stack<T> {
private var first: Node<T>? = null
fun push(content: T) {
if (first == null) {
first = Node(content)
} else {
var node= first
while (node?.next != null) {
node = node.next
}
node?.content = content
}
}}
class Node<T>(var content: T) {
var next: Node<T>? = null
}
marlonlom
05/25/2025, 4:34 PMclass Stack<T> {
private var first: Node<T>? = null
fun push(content: T) {
val newNode = Node(content)
newNode.next = first
first = newNode
}
// Optional: Pop to make it more complete
fun pop(): T? {
val content = first?.content
first = first?.next
return content
}
}
class Node<T>(val content: T) {
var next: Node<T>? = null
}Key Changes: 1. Push now inserts at the beginning — this is the typical stack behavior. 2. Introduced pop() for completeness (optional). 3. Removed unnecessary traversal of the list (which is inefficient for a stack).
Klitos Kyriacou
05/27/2025, 10:33 AMclass Stack<T> {
private var first: Node<T>? = null
fun push(content: T) {
if (first == null) {
first = Node(content)
} else {
var node= first
while (node?.next != null) {
node = node.next
}
node?.content = content
At the last line above, node
points to the last existing node. What this line does is to change the value of the last node to the passed value. You don't want to do that; you want to add a new value to the end. You do that by setting node?.next
to a new Node(content)
.