-
Notifications
You must be signed in to change notification settings - Fork 13
/
StackLinkedList.py
70 lines (57 loc) · 1.56 KB
/
StackLinkedList.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, value=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def __iter__(self):
currNode = self.head
while currNode:
yield currNode
currNode = currNode.next
class Stack:
def __init__(self):
self.LinkedList = LinkedList()
def __str__(self):
values = [str(x.value) for x in self.LinkedList]
return '\n'.join(values)
# tc and sc -O(1)
def isEmpty(self):
if self.LinkedList.head == None:
return True
else:
return False
# tc and sc -O(1)
def push(self, value):
node = Node(value)
node.next = self.LinkedList.head
self.LinkedList.head = node
# tc and sc -O(1)
def Pop(self):
if self.isEmpty():
return "The stack is empty!"
else:
nodeValue = self.LinkedList.head.value
self.LinkedList.head = self.LinkedList.head.next
return nodeValue
# tc and sc -O(1)
def peek(self):
if self.isEmpty():
return "The stack is empty!"
else:
nodeValue = self.LinkedList.head.value
return nodeValue
def delete(self):
self.LinkedList.head = None
customStack = Stack()
#print(customStack.isEmpty())
customStack.push(1)
customStack.push(4)
customStack.push(7)
print(customStack)
print('______________________')
customStack.Pop()
print(customStack)
print('______________________')
print(customStack.peek())