Skip to content

Instantly share code, notes, and snippets.

@wilfreddesert
Created December 27, 2020 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilfreddesert/5fbe495c97b8843b162d2dfaaa9f691b to your computer and use it in GitHub Desktop.
Save wilfreddesert/5fbe495c97b8843b162d2dfaaa9f691b to your computer and use it in GitHub Desktop.
class LinkedListIterator:
def __init__(self, head):
self.current = head
def __next__(self):
try:
data = self.current.data
except AttributeError:
raise StopIteration
self.current = self.current.next_
return data
def __iter__(self):
return self
class Node:
def __init__(self, data=None, next_=None):
self.data = data
self.next_ = next_
class LinkedList:
def __init__(self, sequence=None):
if sequence is not None:
sequence = list(sequence)
first = Node(sequence[0])
self.head = first
current = self.head
current.next_ = Node(sequence[1])
for item in sequence[1:-1]:
current.next_ = Node(data=item)
current = current.next_
last = Node(sequence[-1])
current.next_ = last
self.tail = last
else:
self.head = None
self.tail = None
def append(self, data):
new_node = Node(data=data)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
self.tail.next_ = new_node
self.tail = new_node
def __eq__(self, other):
first = self.head
second = other.head
while first and second:
if first.data != second.data:
return False
first = first.next_
second = second.next_
return True
def __iter__(self):
return LinkedListIterator(self.head)
def __repr__(self):
items = [item for item in self]
return f"LinkedList({str(items)})"
def __getitem__(self, key):
length = len(self)
if key < 0:
key = length - abs(key)
for index, item in enumerate(self):
if index == key:
return item
def __len__(self):
count = 0
for item in self:
count += 1
return count
# def sort(self):
# first = self.head
# second = self.head.next_
# while first:
# if second.data < first.data:
# first.next_ = second._next
# second.next_ = first
# first = first.next_
# second = second.next_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment