-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue(Solution by LinkedList).py
98 lines (73 loc) · 1.74 KB
/
Queue(Solution by LinkedList).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
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
#!/usr/bin/env python
# coding: utf-8
# In[1]:
## 建立空間節點
class Node:
def __init__(self,x):
self.x=x
self.next=None
## Queue以FIFO為原則
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.head=None
self.tail=None
## 考慮因素:
## 1. 若head不存在,代表需要建立第一項
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
new=Node(x)
if(self.head==None):
self.head=new
self.tail=new
else:
current=self.head
while(current.next!=None):
current=current.next
current.next=Node(x)
self.tail=current.next
## 考慮因素:
## 1.
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if(self.head==None):
return -1
else:
current=self.head
to_return=self.head.x
if(current==self.tail):
self.head=None
self.tail=None
else:
self.head=current.next
current=None
return to_return
def peek(self) -> int:
"""
Get the front element.
"""
return self.head.x
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
if(self.head==None):
return True
else:
return False
# In[2]:
MyQueue=MyQueue()
MyQueue.push(1)
MyQueue.push(2)
# In[3]:
MyQueue.peek()
# In[4]:
MyQueue.pop()
# In[5]:
MyQueue.empty()