1# Python program for linked list implementation of stack
2
3# Class to represent a node
4
5
6class StackNode:
7
8 # Constructor to initialize a node
9 def __init__(self, data):
10 self.data = data
11 self.next = None
12
13
14class Stack:
15
16 # Constructor to initialize the root of linked list
17 def __init__(self):
18 self.root = None
19
20 def isEmpty(self):
21 return True if self.root is None else False
22
23 def push(self, data):
24 newNode = StackNode(data)
25 newNode.next = self.root
26 self.root = newNode
27 print "% d pushed to stack" % (data)
28
29 def pop(self):
30 if (self.isEmpty()):
31 return float("-inf")
32 temp = self.root
33 self.root = self.root.next
34 popped = temp.data
35 return popped
36
37 def peek(self):
38 if self.isEmpty():
39 return float("-inf")
40 return self.root.data
41
42
43# Driver code
44stack = Stack()
45stack.push(10)
46stack.push(20)
47stack.push(30)
48
49print "% d popped from stack" % (stack.pop())
50print "Top element is % d " % (stack.peek())
51
52