The stack data structure is a fundamental abstract data type commonly used in computer science and software engineering. It follows the Last-In, First-Out (LIFO) principle, meaning that the last element added to the stack is the first one to be removed. Think of it like a stack of plates: you can only add or remove plates from the top of the stack.
Stack of pancakes
Basic Operations
Push: Adding an element to the top of the stack.
Pop: Removing the top element from the stack.
Peek (or Top): Viewing the top element of the stack without removing it.
isEmpty: Checking if the stack is empty.
Size: Returning the number of elements currently in the stack.
Implementations
Stacks can be implemented using various data structures, including arrays and linked lists.
Arrays are commonly used for implementing stacks due to their simplicity and constant-time access to elements.
Linked lists can also be used, providing dynamic memory allocation and flexibility.
A stack implemented using an array
classStack:
def__init__(self, data):
self.stack = []
if data:
self.stack.append(data)
defadd(self, data):
self.stack.append(data)
defpop(self):
return self.stack.pop()
defpeek(self):
if self.isEmpty():
raiseValueError("The stack is empty")
return self.stack[-1]
defisEmpty(self):
return len(self.stack) ==0
A linked list is a linear collection of data elements, their order is not given by their physical placement in memory. Instead they are constructed in such a way that each element points to the next. It is a data structure that consists of a collection of nodes which together represents a sequence.