forked from jwarren116/data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.py
47 lines (39 loc) · 1.42 KB
/
queue.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
#!/usr/bin/env python
class QueueItem(object):
def __init__(self, data, prev_item=None, next_item=None):
self.data = data
self.next_item = next_item
self.prev_item = prev_item
def __str__(self):
return str(self.data)
class Queue(object):
def __init__(self, first_item=None, last_item=None):
self.first_item = first_item
self.last_item = last_item
def enqueue(self, val):
# adds val to beginning of queue
new_item = QueueItem(val, next_item=self.last_item)
if not self.first_item:
self.first_item = self.last_item = new_item
else:
self.last_item.prev_item = new_item
self.last_item = new_item
def dequeue(self):
# pops last value from list and returns it
obsolete_item = self.first_item
if self.first_item is None:
raise ValueError("No items in queue!")
elif self.last_item is obsolete_item:
self.first_item = self.last_item = None
else:
obsolete_item.prev_item.next_item = None
self.first_item = self.first_item.prev_item
return obsolete_item.data
def size(self):
# returns size of the queue, returns 0 if empty
size = 0
current_item = self.last_item
while current_item is not None:
size += 1
current_item = current_item.next_item
return size