MCPcopy
hub / github.com/keon/algorithms / LinkedListStack

Class LinkedListStack

algorithms/data_structures/stack.py:137–197  ·  view source on GitHub ↗

Stack implemented with a singly linked list. Examples: >>> s = LinkedListStack() >>> s.push(1) >>> s.pop() 1

Source from the content-addressed store, hash-verified

135
136
137class LinkedListStack(AbstractStack):
138 """Stack implemented with a singly linked list.
139
140 Examples:
141 >>> s = LinkedListStack()
142 >>> s.push(1)
143 >>> s.pop()
144 1
145 """
146
147 def __init__(self) -> None:
148 super().__init__()
149 self.head: StackNode | None = None
150
151 def __iter__(self) -> Iterator[object]:
152 probe = self.head
153 while True:
154 if probe is None:
155 return
156 yield probe.value
157 probe = probe.next
158
159 def push(self, value: object) -> None:
160 """Push a value onto the stack.
161
162 Args:
163 value: The value to push.
164 """
165 node = StackNode(value)
166 node.next = self.head
167 self.head = node
168 self._top += 1
169
170 def pop(self) -> object:
171 """Remove and return the top element.
172
173 Returns:
174 The top element.
175
176 Raises:
177 IndexError: If the stack is empty.
178 """
179 if self.is_empty():
180 raise IndexError("Stack is empty")
181 value = self.head.value
182 self.head = self.head.next
183 self._top -= 1
184 return value
185
186 def peek(self) -> object:
187 """Return the top element without removing it.
188
189 Returns:
190 The top element.
191
192 Raises:
193 IndexError: If the stack is empty.
194 """

Callers 1

Calls

no outgoing calls

Tested by 1