Skip to content

Instantly share code, notes, and snippets.

@Jiler01
Created December 10, 2023 15:11
Show Gist options
  • Save Jiler01/2d3fec06d3969882083973a9f06dc705 to your computer and use it in GitHub Desktop.
Save Jiler01/2d3fec06d3969882083973a9f06dc705 to your computer and use it in GitHub Desktop.
Some easy-to-use FIFO/LIFO implementation in python
class Maillon:
def __init__(self, before, value, next):
self.before = before
self.value = value
self.next = next
def set_next(self, value):
self.next = value
def set_before(self, value):
self.before = value
class File:
def __init__(self, *args, mode: str = None):
'''
Mode:str default mode for self.take(): either 'FIFO' or 'LIFO'
'''
self.len = 0
self.begining = Maillon(None, None, None)
self.end = Maillon(self.begining, None, None)
self.begining.set_next(self.end)
self.mode = mode
if self.mode == 'FIFO':
self.take = self.take_first_in
elif self.mode == 'LIFO':
self.take = self.take_last_in
for el in args:
self.add(el)
def add(self, value):
self.begining.set_next(
Maillon(self.begining, value, self.begining.next))
self.begining.next.next.set_before(self.begining.next)
self.len += 1
def take_first_in(self):
if self.end.before == self.begining:
return None
val = self.end.before.value
self.end.before.before.set_next(self.end)
self.end.set_before(self.end.before.before)
self.len -= 1
return val
def take_last_in(self):
if self.begining.next == self.end:
return None
val = self.begining.next.value
self.begining.next.next.set_before(self.begining)
self.begining.set_next(self.begining.next.next)
self.len -= 1
return val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment