How do you implement a stack with a singly-linked list so that every operation is $O(1)$, and which end of the list is the top?
Make the head of the list the top of the stack: push is addFirst, pop is removeFirst, top reads the head's element, and a size counter answers size() — all $O(1)$, with no capacity limit.
The choice of end is the whole design decision. A singly-linked list can add and remove at its head in $O(1)$, but it can only add at its tail in $O(1)$; removing the tail node needs a walk to find its predecessor. A stack must add and remove at the same end, so that end has to be the head.
def push(self, element):
new_node = self._Node(element)
new_node.append_node(self._top) # new node points to the old top
self._top = new_node
self._size += 1
def pop(self):
if self._size == 0:
raise EmptyStackException("stack is empty")
top_node = self._top
self._top = top_node.get_next()
self._size -= 1
return top_node.get_element()
Compared to the array-based stack, the linked version never runs full: memory grows one node at a time. The cost is an extra reference stored per element, plus allocating a node object on every push.
size() is $O(1)$ only because a counter is maintained on every push and pop. Counting the nodes on demand would be $O(n)$.
Go deeper:
Stack visualisation, linked-list (USF) — push and pop happen at the head of the chain.