A Stack is linear structure where insertions and deletions are done at one end called top of the stack. The principle of stack is LIFO, the lastly inserted element is deleted first.
Here are two implementations of stack using arrays. The first one uses arrays standard methods: append() and pop() to implement and the second one uses user defined functions.
1. Using Python array standard methods
# Python program to # demonstrate stack implementation # using list stack = [] # append() function to push # element in the stack stack.append('10') stack.append('20') stack.append('30') print('Initial stack') print(stack) # pop() function to pop # element from stack in # LIFO order print('\nElements popped from stack:') print(stack.pop()) print(stack.pop()) print(stack.pop()) print('\nStack after elements are popped:') print(stack)
Output
Initial stack ['10', '20', '30'] Elements popped from stack: 30 20 10 Stack after elements are popped: []
2. Using user defined functions
# Creating a stack def create(): stack = [] return stack # Creating an empty stack def is_empty(stack): return len(stack) == 0 # Adding items into the stack def push(stack, item): stack.append(item) print("pushed item: " + item) # Removing an element from the stack def pop(stack): if (is_empty(stack)): { print("stack is empty") } return stack.pop() stack = create() push(stack, str(1)) #converting number to string using str() push(stack, str(2)) push(stack, str(3)) push(stack, str(4)) print("-----------------------") print("popped item: " + pop(stack)) print("popped item: " + pop(stack)) print("popped item: " + pop(stack)) print("popped item: " + pop(stack)) print("---------------------") print("stack after popping an element: " + str(stack))
Output
pushed item: 1 pushed item: 2 pushed item: 3 pushed item: 4 ----------------------- popped item: 4 popped item: 3 popped item: 2 popped item: 1 --------------------- stack after popping an element: []
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.