-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathIntroduction.py
More file actions
80 lines (63 loc) · 1.69 KB
/
Copy pathIntroduction.py
File metadata and controls
80 lines (63 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
'''-->It is a linear data structure.
-->Follows a paarticular order in which the operations are performed.'
-->Order may be FILO or LIFO
-->Main operations are
1)push-->Add an item in the stack
2)pop-->removes an item in the stack
3)peek-->get the topmost item.
-->stack may be implemented using two ways:
1)using linked list
2)using arrays
'''
from sys import maxsize
#fucntion to create Stack
def createStack():
stack = []
return stack
def isEmpty(stack):
return len(stack) == 0
def push(stack,item):
stack.append(item)
print "pushed to stack" + item
def pop(stack):
if isEmpty(stack):
return str(-maxsize-1)
return stack.pop()
stack = createStack()
push(stack,str(10))
push(stack,str(20))
push(stack,str(30))
push(stack,str(40))
print pop(stack) + "Popped from stack"
#Implementing stack using linkedList
class StackNode:
def __init__(self,data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.root = None
def isEmpty(self):
return True is self.root is None else False
def push(self,data):
new_node = StackNode(data)
new_node.next = self.root
self.root = new_node
def pop(self):
if self.isempty():
return float("-inf")
temp = self.root
self.root = self.root.next
Popped = temp.data
return Popped
def peek(self):
if self.isEmpty():
return float("-inf")
return self.root.data
#Driver program to test above class
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
print "%d popped from stack" %(stack.pop())
print "Top element is %d" % (stack.peek())