Junior — Middle
What processes occur when a new element is added to a stack implemented via a linked list?
sobes.tech AI
Answer from AI
When adding a new element to a stack implemented via a linked list, the following occurs:
- A new node (list element) is created, which stores the value to be added.
- The pointer of the new node is set to the current top element of the stack (i.e., the head of the linked list).
- The head of the linked list is updated to point to the new node — it becomes the new top element of the stack.
Thus, the push operation is performed in constant time O(1), as it does not require traversing the list.
Example in Kotlin:
class Node<T>(val value: T, var next: Node<T>? = null)
class Stack<T> {
private var head: Node<T>? = null
fun push(value: T) {
val newNode = Node(value)
newNode.next = head
head = newNode
}
fun pop(): T? {
val value = head?.value
head = head?.next
return value
}
}