-
Notifications
You must be signed in to change notification settings - Fork 17
/
design-front-middle-back-queue.py
131 lines (88 loc) · 2.79 KB
/
design-front-middle-back-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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
from typing import Optional
class ListNode:
def __init__(self, val: int) -> None:
self.val = val
self.next: Optional[ListNode] = None
self.prev: Optional[ListNode] = None
class FrontMiddleBackQueue:
def __init__(self):
self.head = ListNode(-123)
self.tail = ListNode(123)
self.head.next = self.tail
self.tail.prev = self.head
self.middle = self.tail
self.nodes = 2
def pushFront(self, val: int) -> None:
node = ListNode(val)
head_next = self.head.next
self.head.next = node
node.prev = self.head
node.next = head_next
head_next.prev = node
self.nodes += 1
if self.nodes % 2 == 1:
self.middle = self.middle.prev
def pushMiddle(self, val: int) -> None:
node = ListNode(val)
prev = self.middle.prev
prev.next = node
node.prev = prev
node.next = self.middle
self.middle.prev = node
self.nodes += 1
if self.nodes % 2 == 1:
self.middle = self.middle.prev
def pushBack(self, val: int) -> None:
node = ListNode(val)
prev_node = self.tail.prev
prev_node.next = node
node.prev = prev_node
node.next = self.tail
self.tail.prev = node
self.nodes += 1
if self.nodes % 2 == 0:
self.middle = self.middle.next
if self.nodes == 3:
self.middle = node
def popFront(self) -> int:
if self.nodes < 3:
return -1
value = self.head.next.val
tmp = self.head.next.next
self.head.next = tmp
tmp.prev = self.head
self.nodes -= 1
if self.nodes % 2 == 0:
self.middle = self.middle.next
return value
def popMiddle(self) -> int:
if self.nodes < 3:
return -1
middle = self.middle if self.nodes % 2 == 1 else self.middle.prev
prev_node = middle.prev
next_node = middle.next
prev_node.next = next_node
next_node.prev = prev_node
self.middle = middle.next
self.nodes -= 1
return middle.val
def popBack(self) -> int:
if self.nodes < 3:
return -1
if self.nodes == 3:
return self.popMiddle()
value = self.tail.prev.val
tmp = self.tail.prev.prev
tmp.next = self.tail
self.tail.prev = tmp
self.nodes -= 1
if self.nodes % 2 == 1:
self.middle = self.middle.prev
return value
# Your FrontMiddleBackQueue object will be instantiated and called as such:
# obj = FrontMiddleBackQueue()
# obj.pushFront(val)
# obj.pushMiddle(val) # obj.pushBack(val)
# param_4 = obj.popFront()
# param_5 = obj.popMiddle()
# param_6 = obj.popBack()