Repository navigation
Expand file tree
/
Copy pathqueue.py
More file actions
74 lines (55 loc) · 2.17 KB
/
Copy pathqueue.py
File metadata and controls
74 lines (55 loc) · 2.17 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
"""
A queue is a data structure whose primary purpose is to store and
return elements in First In First Out order.
1. Implement the Queue class using an array as the underlying storage structure.
Make sure the Queue tests pass.
2. Re-implement the Queue class, this time using the linked list implementation
as the underlying storage structure.
Make sure the Queue tests pass.
3. What is the difference between using an array vs. a linked list when
implementing a Queue?
Stretch: What if you could only use instances of your Stack class to implement the Queue?
What would that look like? How many Stacks would you need? Try it!
"""
class Queue:
def __init__(self):
self.size = 0
self.storage = []
def __len__(self):
return self.size
def enqueue(self, value):
self.size += 1
self.storage.append(value)
def dequeue(self):
if self.size != 0:
self.size -= 1
return self.storage.pop(0)
# 2. Re-implement the Queue class, this time using the linked list implementation
# as the underlying storage structure.
# Make sure the Queue tests pass.
from singly_linked_list import LinkedList
class Quene1():
def __init__(self):
self.size = 0
self.storage = LinkedList()
def __len__(self):
return self.size
def equeue(self, value):
self.size +=1
self.storage.add_to_tail(value)
def dequeue(self):
# != : means the list is not empty and there are elements
if self.size != 0:
# -= : removing one element at a time.
self.size -= 1
return self.storage.remove_head()
"""
3. What is the difference between using an array vs. a linked list when
implementing a Queue?
When implementing a queue, we have to remove the first element and/or add
a new element as the last element if we use an array
When using a linked list, we have to add an element to the tail,
therefore changing the address of the last element and of the tail.
If we have to dequeue, we have to remove the head, and then to reallocate
an address to every other elements.
"""