-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathStack Implementation.py
More file actions
72 lines (66 loc) · 1.87 KB
/
Copy pathStack Implementation.py
File metadata and controls
72 lines (66 loc) · 1.87 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
#Python program for implementation of stack using linked list
#Class to represent node
class Node:
#constructor to intialize node
def __init__(self,data):
self.data=data
self.next=None
class Stack:
#Constructor to intialize root of linked list
def __init__(self,root):
self.root=None
def isempty(self):
return True if self.root is None else False
def push(data):
newnode=Node(data)
newnode.next=root
root=newnode
def pop():
if isempty():
return 0
temp=root
root=root.next
popped=temp.data
return popped
def peek():
if isempty():
return 0
return root.data
#program to test above function
stack=stack()
stack.push(5)
stack.push(10)
stack.push(15)
print stack.pop
print stack.peek
#implementing stack using arrays
#import maxsize from sys.Maxsize returns infinite when stack is empty.
from sys import maxsize
#function to create a stack.initial size of stack is zero
def createstack():
stack=[]
return stack
if isempty(stack):
return len(stack)==0
#push function to add an item on the stack.Increases stack size by 1
def push(stack,item):
stack.append(item)
print ("item pushed"+item)
#pop function to remove item from stack.Decreases stack size by 1.
def pop(stack):
if (isempty(stack)):
return str(-maxsize-1)
stack.pop()
#peek function.return top element of the stack
def peek(stack):
if (isempty(stack)):
return str(-maxsize-1)
return stack[-len(stack)-1]
#driver program to test the above functions
stack=createstack()
push(stack,str(10))
push(stack,str(20))
push(stack,str(30))
push(stack,str(40))
print(pop(stack) +" is popped from stack")
print("top item is "+peek(stack))