Queue
  • Queue is a linear structure, the order is First In First Out (FIFO)
  • Operations
  • enqueue(), insert element at the tail
  • dequeue(), delete element at the head
  • front(), return element at head
  • rear(), return element at rear
  • Implementation with array

    Implementation with list
    1. # QueueModule.py
    2. #!/usr/bin/python3
    3. class Queue(object):
    4. def __init__(self):
    5. self.items = []
    6.  
    7. def isEmpty(self):
    8. return len(self.items) == 0
    9.  
    10. def enqueue(self, v):
    11. try:
    12. self.items.insert(0,v)
    13. return True
    14. except Exception as e:
    15. return False
    16.  
    17. def dequeue(self):
    18. try:
    19. item = self.items.pop()
    20. return item
    21. except Exception as e:
    22. return None
    23.  
    24. def size(self):
    25. return len(self.items)
    26.  
    27. def front(self):
    28. if self.size() == 0:
    29. return None
    30. return self.items[self.size()-1]
    31.  
    32. def rear(self):
    33. if self.size() == 0:
    34. return None
    35. return self.items[0]
    36.  
    37. def __str__(self):
    38. s = 'rear ->'
    39.  
    40. output = []
    41.  
    42. for item in self.items:
    43. output.append(str(item))
    44.  
    45. s += '->'.join(output)
    46.  
    47. s += '-> front'
    48.  
    49. return s
    1. #!/usr/bin/python3
    2. from QueueModule import Queue
    3.  
    4. def main():
    5. q = Queue()
    6.  
    7. q.enqueue(4)
    8. q.enqueue('dog')
    9. q.enqueue(True)
    10.  
    11. print(q) # rear ->True->dog->4-> front
    12. print(q.size()) # 3
    13.  
    14. print(q.dequeue()) # 4
    15.  
    16. print(q.front()) # dog
    17. print(q.rear()) # True
    18.  
    19. if __name__ == '__main__':
    20. main()
    Implementation with linked list
    1. #!/usr/bin/python3
    2. """ A model containing Node class """
    3. import copy
    4.  
    5. __author__ = "Lin Chen"
    6. __version__ = "0.1"
    7.  
    8. class Node:
    9. """Single node with double pointers pointing to its previous node and the node after it"""
    10.  
    11. def __init__(self, data):
    12. """Initialize a Node
    13. Args:
    14. data : data saved in the node
    15. """
    16. self._data = data
    17. self._prev = None
    18. self._next = None
    19.  
    20. @property
    21. def data(self):
    22. return self._data
    23.  
    24. @data.setter
    25. def data(self, d):
    26. self._data = d
    27.  
    28. @data.deleter
    29. def data(self):
    30. del self._data
    31.  
    32. @property
    33. def next(self):
    34. return self._next
    35.  
    36. @next.setter
    37. def next(self, n):
    38. self._next = n
    39.  
    40. @next.deleter
    41. def next(self):
    42. del self._next
    43.  
    44. @property
    45. def prev(self):
    46. return self._prev
    47.  
    48. @prev.setter
    49. def prev(self, n):
    50. self._prev = n
    51.  
    52. @prev.deleter
    53. def prev(self):
    54. del self._prev
    55.  
    56. def __str__(self):
    57. return str(self._data)
    Double Linked List
    1. #!/usr/bin/python
    2. """ A modeule containing List class"""
    3.  
    4. from NodeModule import Node
    5.  
    6. class List:
    7. """Linked List class with a pre-defined Node class"""
    8.  
    9. def __init__(self):
    10. """Initialize a List
    11. """
    12. self._head = None
    13. self._tail = None
    14. self._count = 0
    15.  
    16. def getSize(self):
    17. """Return the size of the list
    18. Returns:
    19. int : size of the list
    20. """
    21. return self._count
    22.  
    23. def access(self, index):
    24. """Access a node with its index
    25.  
    26. Args:
    27. index: index of a specified node
    28.  
    29. Returns:
    30. Node: a pointer of the specified node if the specifid node exists; None, otherwise
    31. """
    32. if index < 0 or index > self._count-1:
    33. return None
    34.  
    35. # access the front node
    36. if index == 0:
    37. return self._head
    38.  
    39. # access the tail node
    40. if index == self._count-1:
    41. return self._tail
    42.  
    43. if index <= self.getSize()/2: # access the first half
    44. current = self._head
    45. for i in range(index):
    46. current = current.next
    47. return current
    48. else: # access the second half
    49. current = self._tail
    50. for i in range(self.getSize()-index-1):
    51. current = current.prev
    52. return current
    53.  
    54. return None
    55.  
    56. def insert(self, index, v):
    57. """Insert a valude to make the list maintain ascending order
    58.  
    59. Args:
    60. v : data which can be saved in a node
    61.  
    62. Returns:
    63. Node: True, if the value is inserted succefully; False, otherwise
    64. """
    65. if index < 0 or index > self._count:
    66. return False
    67.  
    68. n = Node(v) # create a node
    69.  
    70. # insert a node into an empty list
    71. if self.getSize() == 0:
    72. self._head = n
    73. self._tail = n
    74. self._count += 1
    75. return True
    76.  
    77. # insert a node in the front
    78. if index == 0:
    79. n.next = self._head
    80. self._head.prev = n
    81. self._head = n
    82. self._count += 1
    83. return True
    84.  
    85. # insert a node at the end
    86. if index == self.getSize():
    87. n.prev = self._tail
    88. self._tail.next = n
    89. self._tail = n
    90. self._count += 1
    91. return True
    92.  
    93. if index <= self.getSize()/2:
    94. current = self._head
    95. for i in range(index-1):
    96. current = current.next
    97. n.next = current.next
    98. n.prev = current
    99. current.next.prev = n
    100. current.next = n
    101. self._count += 1
    102. return True
    103. else:
    104. current = self._tail
    105. for i in range(self.getSize()-index-1):
    106. current = current.prev
    107. n.next = current
    108. n.prev = current.prev
    109. current.prev.next = n
    110. current.prev = n
    111. self._count += 1
    112. return True
    113.  
    114. return False
    115.  
    116. def delete(self, index):
    117. """Delete a valude located at a specific location in the list
    118.  
    119. Args:
    120. index (int): location of deletion, 0 is the location before the first element, 1 is the location after the first element
    121.  
    122. Returns:
    123. boolean: the value of removed node, if the node is deleted succefully; None, otherwise
    124. """
    125. if index < 0 or index > self._count-1:
    126. return None
    127.  
    128. if index == 0:
    129. n = self._head
    130. self._head = self._head.next
    131. self._head.prev = None
    132. self._count -= 1
    133. return n
    134.  
    135. if index == self._count-1:
    136. n = self._tail
    137. self._tail = self._tail.prev
    138. self._tail.next = None
    139. self._count -= 1
    140. return n
    141.  
    142. if index <= self._count/2:
    143. current = self._head
    144. for i in range(index-1):
    145. current = current.next
    146. n = current.next
    147. current.next = current.next.next
    148. current.next.prev = current
    149. self._count -= 1
    150. return n
    151. else:
    152. current = self._tail
    153. for i in range(self.getSize()-index-2):
    154. current = current.prev
    155. n = current.prev
    156. current.prev = current.prev.prev
    157. current.prev.next = current
    158. self._count -= 1
    159. return n
    160.  
    161. return None
    162.  
    163. def __str__(self):
    164. """Convert the list to a string
    165.  
    166. Returns:
    167. string : a string represents the list
    168. """
    169. if self.getSize() == 0:
    170. return "Empty"
    171.  
    172. current = self._head
    173. output = []
    174.  
    175. while current is not None:
    176. output.append(str(current))
    177. current = current.next
    178.  
    179. return " -> ".join(output)
    Queue
    1. #!/usr/bin/python
    2.  
    3. from ListModule import List
    4.  
    5. class Queue(List):
    6. def __init__(self):
    7. List.__init__(self)
    8.  
    9. def enqueue(self, v):
    10. """insert element at the tail
    11.  
    12. Args:
    13. v : data which can be saved in a node
    14. Returns:
    15. boolean: True, if the value is inserted succefully; False, otherwise
    16. """
    17. return self.insert(self.getSize(), v)
    18.  
    19. def dequeue(self):
    20. """delete a node from the front
    21.  
    22. Args:
    23. index (int): location of deletion, 0 is the location before the first element, 1 is the location after the first element
    24.  
    25. Returns:
    26. Node: a pointer of the delete node if the queue is not empty; None, otherwise
    27. """
    28. return self.delete(0)
    29.  
    30. def front(self):
    31. """access the first node in the queue
    32.  
    33. Returns:
    34. Node: a pointer of the first node if the queue is not empty; None, otherwise
    35. """
    36. return self.access(0)
    37.  
    38. def rear(self):
    39. """access the tail node in the queue
    40.  
    41. Returns:
    42. Node: a pointer of the tail node if the queue is not empty; Noen, otherwise
    43. """
    44. return self.access(self._count-1)
    Test
    1. #!/usr/bin/python
    2.  
    3. from QueueModule import Queue
    4.  
    5. def main():
    6. q = Queue()
    7.  
    8. # enqueue
    9. q.enqueue(10)
    10. q.enqueue(20)
    11. q.enqueue(15)
    12. q.enqueue(30)
    13. q.enqueue(40)
    14. print(q)
    15.  
    16. # front
    17. print(q.front().data)
    18.  
    19. # rear
    20. print(q.rear().data)
    21.  
    22. # dequeue
    23. n = q.dequeue() # 10
    24. print(n.data) # the value of remove node
    25. print(q)
    26.  
    27. if __name__ == '__main__':
    28. main()
    Queue Sample
  • A operating system
  • E-mail system