-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathqueue.py
66 lines (56 loc) · 1.31 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
class Queue(object):
head = None
tail = None
def enqueue(self, data):
new_node = Node(data)
if self.tail:
self.tail.next = new_node
self.tail = new_node
if self.head is None:
self.head = self.tail
def dequeue(self):
if self.head is None:
return None
data = self.head.data
self.head = self.head.next
if self.head is None:
self.tail = None
return data
def peek(self):
if self.head is None:
return None
return self.head.data
def is_empty(self):
return self.head is None
if __name__ == "__main__":
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
q.enqueue(4)
print(q.dequeue())
q.enqueue(5)
print(q.peek())
print(q.dequeue())
print(q.dequeue())
print(q.peek())
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
print(q.peek())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.peek())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())