-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.py
More file actions
109 lines (98 loc) · 2.2 KB
/
Stack.py
File metadata and controls
109 lines (98 loc) · 2.2 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
class Stack:
'''
>>> x=Stack()
>>> x.pop()
>>> x.push(2)
>>> x.push(4)
>>> x.push(6)
>>> x
Top:Node(6)
Stack:
6
4
2
>>> x.pop()
6
>>> x
Top:Node(4)
Stack:
4
2
>>> len(x)
2
>>> x.isEmpty()
False
>>> x.push(15)
>>> x
Top:Node(15)
Stack:
15
4
2
>>> x.peek()
15
>>> x
Top:Node(15)
Stack:
15
4
2
'''
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __str__(self):
return "Node({})".format(self.value)
__repr__ = __str__
def __init__(self):
# YOU ARE NOT ALLOWED TO MODIFY THE CONSTRUCTOR
self.top = None
self.count=0
def __str__(self):
# YOU ARE NOT ALLOWED TO MODIFY THE THIS METHOD
temp=self.top
out=[]
while temp:
out.append(str(temp.value))
temp=temp.next
out='\n'.join(out)
return ('Top:{}\nStack:\n{}'.format(self.top,out))
__repr__=__str__
def isEmpty(self):
# YOUR CODE STARTS HERE
if self.top == None:
return True
return False
def __len__(self):
# YOUR CODE STARTS HERE
temp = self.top
c = 0
while temp:
c += 1
temp = temp.next
return c
def push(self,value):
# YOUR CODE STARTS HERE
newNode = self.Node(value)
if len(self) == 0:
self.top = newNode
else:
newNode.next = self.top
self.top = newNode
def pop(self):
# YOUR CODE STARTS HERE
if len(self) == 0:
return None
if len(self) == 1:
value = self.top.value
self.top = None
return value
value = self.top.value
self.top = self.top.next
return value
def peek(self):
# YOUR CODE STARTS HERE
if len(self) == 0:
return None
return self.top.value