Wednesday, 8 May 2019

Simple example demonstrating the stack data structure with Python list

The essential principle of thesStack data structure is "LIFO _ Last In First Out". The last item that is PUSHED into the stack is the first item that will be POPPED out.
In Python, the built-in list data structure, has the append() function that can be used as PUSH function of a stack; it also has the pop() function that can be used as POP function of a stack.
The following source code demonstrates the usage of Python list as a stack.
#reverse list of numbers using stack in Python
def revList(aList):
stack = []
returnList = []
for item in aList:
stack.append(item)
while len(stack) > 0:
returnList.append(stack.pop())
return returnList
aList = [1,2,3,4]
print(revList(aList))
view raw simple_stack.py hosted with ❤ by GitHub

No comments:

Post a Comment