Skip to content

Commit d7d0e97

Browse files
authored
Create Stack.py
1 parent cd68b57 commit d7d0e97

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

DataStructure/Stack.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class StackNode:
2+
3+
# Constructor to initialize a node
4+
def __init__(self, data):
5+
self.data = data
6+
self.next = None
7+
8+
class Stack:
9+
10+
# Constructor to initialize the root of linked list
11+
def __init__(self):
12+
self.root = None
13+
14+
def isEmpty(self):
15+
return True if self.root is None else False
16+
17+
def push(self, data):
18+
newNode = StackNode(data)
19+
newNode.next = self.root
20+
self.root = newNode
21+
print "%d pushed to stack" %(data)
22+
23+
def pop(self):
24+
if (self.isEmpty()):
25+
return float("-inf")
26+
temp = self.root
27+
self.root = self.root.next
28+
popped = temp.data
29+
return popped
30+
31+
def peek(self):
32+
if self.isEmpty():
33+
return float("-inf")
34+
return self.root.data
35+
36+
# Driver program to test above class
37+
stack = Stack()
38+
stack.push(10)
39+
stack.push(20)
40+
stack.push(30)
41+
42+
print "%d popped from stack" %(stack.pop())
43+
print "Top element is %d " %(stack.peek())

0 commit comments

Comments
 (0)