forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
implementation of ArrayQueue and CircularQueue in Python
- Loading branch information
1 parent
34b568f
commit 13d6ce3
Showing
2 changed files
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
""" | ||
Queue based upon array | ||
用数组实现的队列 | ||
Author: Wenru | ||
""" | ||
|
||
from typing import Optional | ||
|
||
class ArrayQueue: | ||
|
||
def __init__(self, capacity: int): | ||
self._items = [] | ||
self._capacity = capacity | ||
self._head = 0 | ||
self._tail = 0 | ||
|
||
def enqueue(self, item: str) -> bool: | ||
if self._tail == self._capacity: return False | ||
|
||
self._items.append(item) | ||
self._tail += 1 | ||
return True | ||
|
||
def dequeue(self) -> Optional[str]: | ||
if self._head != self._tail: | ||
item = self._items[self._head] | ||
self._head += 1 | ||
return item | ||
|
||
def __repr__(self) -> str: | ||
return " ".join(item for item in self._items[self._head : self._tail]) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
""" | ||
Author: Wenru | ||
""" | ||
|
||
from typing import Optional | ||
from itertools import chain | ||
|
||
class CircularQueue: | ||
|
||
def __init__(self, capacity): | ||
self._items = [] | ||
self._capacity = capacity + 1 | ||
self._head = 0 | ||
self._tail = 0 | ||
|
||
def enqueue(self, item: str) -> bool: | ||
if (self._tail + 1) % self._capacity == self._head: | ||
return False | ||
|
||
self._items.append(item) | ||
self._tail = (self._tail + 1) % self._capacity | ||
return True | ||
|
||
def dequeue(self) -> Optional[str]: | ||
if self._head != self._tail: | ||
item = self._items[self._head] | ||
self._head = (self._head + 1) % self._capacity | ||
return item | ||
|
||
def __repr__(self) -> str: | ||
if self._tail >= self._head: | ||
return " ".join(item for item in self._items[self._head : self._tail]) | ||
else: | ||
return " ".join(item for item in chain(self._items[self._head:], self._items[:self._tail])) | ||
|
||
if __name__ == "__main__": | ||
q = CircularQueue(5) | ||
for i in range(5): | ||
q.enqueue(str(i)) | ||
q.dequeue() | ||
q.dequeue() | ||
q.enqueue(str(5)) | ||
print(q) |