Skip to content

Commit

Permalink
implementation of ArrayQueue and CircularQueue in Python
Browse files Browse the repository at this point in the history
  • Loading branch information
jerryderry committed Oct 9, 2018
1 parent 34b568f commit 13d6ce3
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
33 changes: 33 additions & 0 deletions python/09_queue/array_queue.py
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])

43 changes: 43 additions & 0 deletions python/09_queue/circular_queue.py
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)

0 comments on commit 13d6ce3

Please sign in to comment.