-
Notifications
You must be signed in to change notification settings - Fork 26
/
Stack Implemention in python.py
70 lines (56 loc) · 1.42 KB
/
Stack Implemention in python.py
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
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
self.stackSize = 0
def push(self, data):
temp = Node(data)
if self.top is None:
self.top = temp
self.stackSize = self.stackSize + 1
else:
temp.next = self.top
self.top = temp
self.stackSize = self.stackSize + 1
def pop(self):
try:
if self.top == None:
raise Exception("Stack is Empty")
else:
temp = self.top
self.top = self.top.next
tempdata = temp.data
self.stackSize = self.stackSize - 1
del temp
return tempdata
except Exception as e:
print(str(e))
def isEmpty(self):
if self.stackSize == 0:
return True
else:
return False
def size(self):
return self.stackSize
def top_element(self):
try:
if self.top == None:
raise Exception("Stack is Empty")
else:
return self.top.data
except Exception as e:
print(str(e))
s = Stack()
s.push(1)
print(s.size())
s.push(2)
print(s.size())
print(s.pop())
print(s.size())
print(s.pop())
print(s.stackSize)
print(s.top_element())
print(s.isEmpty())