Sobes.tech
Junior — Middle

How can a stack data structure be built using a linked list?

sobes.tech AI

Answer from AI

A stack can be implemented based on a linked list, where each element (node) contains data and a reference to the next element. The top element of the stack is the head of the list. Main operations:

  • push — add a new node to the beginning of the list;
  • pop — remove the node from the beginning of the list and return its value;
  • peek — view the value of the head without removing it.

Example in Kotlin:

class Node<T>(val data: T, var next: Node<T>? = null)

class Stack<T> {
    private var head: Node<T>? = null

    fun push(value: T) {
        val newNode = Node(value, head)
        head = newNode
    }

    fun pop(): T? {
        val value = head?.data
        head = head?.next
        return value
    }

    fun peek(): T? = head?.data

    fun isEmpty() = head == null
}

This approach provides stack operations in O(1) time and allows dynamic expansion without the need to allocate a large array.