A stack is a Last-In, First-Out (LIFO) data structure: the most recently added element is the first one removed. Implementing a stack with a linked list is a simple and efficient way to support constant-time insertion and removal at the top by using the list’s head as the stack top.
Structure Node:
value
next
Structure StackLL:
head = null
n = 0
push(x):
node = new Node
node.value = x
node.next = head
head = node
n = n + 1
pop():
if head is null: raise Underflow
x = head.value
head = head.next
n = n - 1
return x
peek():
if head is null: raise Underflow
return head.value
is_empty():
return head is null
size():
return n
Visual intuition:
top -> [value: 7 | next] -> [value: 3 | next] -> [value: 1 | next] -> null
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class StackLL:
def __init__(self):
self._head = None
self._size = 0
def push(self, x):
self._head = Node(x, self._head)
self._size += 1
def pop(self):
if self._head is None:
raise IndexError
x = self._head.value
self._head = self._head.next
self._size -= 1
return x
def peek(self):
if self._head is None:
raise IndexError
return self._head.value
def is_empty(self):
return self._head is None
def __len__(self):
return self._size