Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
refactored ring buffer to work better
  • Loading branch information
AustinHadden committed Mar 27, 2020
commit 78c8dc1ec746932518fad1a5a8032432fbdb9150
53 changes: 21 additions & 32 deletions ring_buffer/ring_buffer.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from doubly_linked_list import DoublyLinkedList, ListNode
from doubly_linked_list import DoublyLinkedList


class RingBuffer:
Expand All @@ -8,43 +8,32 @@ def __init__(self, capacity):
self.storage = DoublyLinkedList()

def append(self, item):
if self.storage.length == 0:
self.storage.add_to_head(item)
self.current = self.storage.head
elif self.storage.length < self.capacity:
if len(self.storage) == 0:
self.storage.add_to_tail(item)
self.current = self.storage.tail
return

if (len(self.storage)) == self.capacity and self.storage.tail.next is None:
self.storage.tail.next = self.storage.head

if self.storage.tail.next is None:
self.storage.add_to_tail(item)
self.current = self.current.next
else:
if self.current is self.storage.head:
self.storage.remove_from_head()
self.storage.add_to_head(item)
if self.storage.head.next:
self.current = self.storage.head.next
else:
self.current = self.storage.head
elif self.current is self.storage.tail:
self.storage.remove_from_tail()
self.storage.add_to_tail(item)
self.current = self.storage.head
else:
current_next = self.current.next
current_prev = self.current.prev
self.storage.delete(self.current)
new_node = ListNode(item)
new_node.next = current_next
new_node.prev = current_prev
current_next.prev = new_node
current_prev.next = new_node
self.storage.length += 1
self.current = new_node.next
self.current = self.current.next
self.current.value = item

def get(self):
# Note: This is the only [] allowed
list_buffer_contents = []
temp = self.storage.head
list_buffer_contents.append(temp.value)
while temp.next:
temp = temp.next
list_buffer_contents.append(temp.value)
cursor = self.storage.head
list_buffer_contents.append(cursor.value)
cursor = cursor.next
while cursor is not self.storage.head:
list_buffer_contents.append(cursor.value)
if cursor.next is None:
break
cursor = cursor.next

return list_buffer_contents

Expand Down