Data structures organize storage in computers so that we can efficiently access and change data. Stacks and Queues are some of the earliest data structures defined in computer science.
Stacks, like the name suggests, follow the Last-in-First-Out (LIFO) principle. It is a linear data structure which follows a particular order in which the operations are performed. As if stacking plates one on top of the other, the last plate we put on the top is the one that is the first to be removed from the stack later.
Push
- Adds an element to the top of the stack.Pop
- Removes the element at the top of the stack.Peek
or top
- Look at the top of the stackstack = []
def top(stack):
if stack != []:
print("{} is top element".format(stack[-1]))
else:
print("Stack Empty!!!")
def size(stack):
print("Size of stack is {}".format(len(stack)))
def empty(stack):
if stack == []:
return True
else:
return False
Push
element into stack¶def push(stack, value):
stack.append(value)
print("Pushed {} into stack".format(value))
Pop
elements from stack¶def pop(stack):
if not empty(stack):
print("{} is popped".format(stack.pop()))
else:
print("Cannot Pop since stack is empty")
def show_stack(stack):
print("Full stack is {}".format(stack))
# Pushing elements into a stack
push(stack, 1)
push(stack, 2)
push(stack, 3)
# Printing stack
show_stack(stack)
# Printing stack size
size(stack)
# Printing top of stack
top(stack)
# Popping elements from a stack
pop(stack)
show_stack(stack)
# Check if stack is empty
empty(stack)
# More popping elements from a stack
pop(stack)
pop(stack)
# The below line would fail since there are no more elements to pop from a stack
pop(stack)
show_stack(stack)
empty(stack)
Pushed 1 into stack Pushed 2 into stack Pushed 3 into stack Full stack is [1, 2, 3] Size of stack is 3 3 is top element 3 is popped Full stack is [1, 2] 2 is popped 1 is popped Cannot Pop since stack is empty Full stack is []
True