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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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)) |
No comments:
Post a Comment