Skip to content

Instantly share code, notes, and snippets.

@LucasMagnum
Created August 20, 2018 17:49
Show Gist options
  • Save LucasMagnum/1e0d8f0a3d13b3410f199f5d185086b2 to your computer and use it in GitHub Desktop.
Save LucasMagnum/1e0d8f0a3d13b3410f199f5d185086b2 to your computer and use it in GitHub Desktop.
Singly Linked List - Python Implement (Tail reference)
class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next_node = next_node
def __str__(self):
return f"Node(value={self.value})"
class LinkedList:
"""
LinkedList implementation.
Example:
>> linked_list = LinkedList()
>> linked_list.append(1)
>> linked_list.append(2)
>> linked_list.remove(1)
"""
def __init__(self):
self.head = None
self.tail = None
def __str__(self):
values = []
current_node = self.head
while current_node:
values.append(current_node.value)
current_node = current_node.next_node
return ",".join(map(str, values))
def append(self, value):
"""Append a value in the end of the list."""
new_node = Node(value)
if self.is_empty():
self.head = new_node
else:
last_node = self.tail
last_node.next_node = new_node
self.tail = new_node
def prepend(self, value):
"""Prepend in the begin of the list"""
new_node = Node(value, next_node=self.head)
self.head = new_node
def pop(self):
"""Pop the last element in the list"""
current_node = self.head
previous_node = None
while current_node:
if not current_node.next_node:
# We are poping the `head` of the list
if not previous_node:
self.head = None
else:
previous_node.next_node = None
return current_node
previous_node = current_node
current_node = current_node.next_node
def popFirst(self):
"""Pop the first element in the list"""
current_node = self.head
if current_node:
self.head = current_node.next_node
return current_node
def remove(self, value):
"""Remove a given node from the list"""
current_node = self.head
previous_node = None
while current_node:
if current_node.value == value:
# We are removing the head
if not previous_node:
self.head = None
else:
previous_node.next_node = None
return current_node
current_node = current_node.next
previous_node = current_node
def is_empty(self):
return True if not self.head else False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment