Skip to content

Commit

Permalink
stack.py: Add Stack Data Structure
Browse files Browse the repository at this point in the history
This adds Stack data structure in Python Language.
Includes basic functionality of stack (push, pop, top, display).

Closes #37
  • Loading branch information
shreyasbapat authored and sangamcse committed Oct 2, 2018
1 parent 3ca5152 commit 9f57bb2
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ This repository contains examples of various algorithms written on different pro
| Data Structure | C | CPP | Java | Python |
|:----------------------------------------------------------------------------------------------- |:-------------------------------------:|:-------------------------------------:|:-------------------------------------:|:-------------------------------------:|
| [Queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) | | [:octocat:](queue/Cpp) | | |
| [Stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) | | | [:octocat:](stack/Java) | |
| [Stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) | | | [:octocat:](stack/Java) | [:octocat:](stack/Python) |
| [Linear Linked List](https://en.wikipedia.org/wiki/Linked_list) | [:octocat:](linked_list/C) | | | |
| [AVL Tree](https://en.wikipedia.org/wiki/AVL_tree) | | | [:octocat:](avl_tree/Java) | |

Expand Down
63 changes: 63 additions & 0 deletions stack/Python/stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
class Stack:
"""
Class for operations related to stack.
"""

def __init__(self):

self.stack = [] # Initialise empty stack

def push(self, dataval):
"""
Method to push items in stack.
:param dataval: Value that user needs to push.
"""

self.stack.append(dataval)

def pop(self):
"""
Method for removing the last element from the stack.
:return: Element that is popped.
"""

if len(self.stack) <= 0:
# Raise an error if stack is empty.
return "No element in the Stack"

else:
return self.stack.pop()

def top(self):
"""
Method to show the last element of the stack.
:return: last element of the stack.
"""

return self.stack[len(self.stack)-1]

def display(self):
"""
Method to print all elements of the stack.
"""

print(*self.stack)


def main():
AStack = Stack()
AStack.push("Mon")
AStack.push("Tue")
AStack.pop()
AStack.push("Wed")
m = AStack.top()
print(m)
AStack.push("Thu")
AStack.display()


if __name__ == "__main__":
main()

0 comments on commit 9f57bb2

Please sign in to comment.