Created
August 20, 2018 17:29
-
-
Save LucasMagnum/d87000759e82208260e566a2740a0178 to your computer and use it in GitHub Desktop.
Singly Linked List - Python Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
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 | |
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 tail(self): | |
"""Return the last node in the list.""" | |
last_node = self.head | |
while last_node and last_node.next_node: | |
last_node = last_node.next_node | |
return last_node | |
def is_empty(self): | |
return True if not self.head else False | |
def __str__(self): | |
"""This is a helper function to print the list, do not focus here.""" | |
values = [] | |
current_node = self.head | |
while current_node: | |
values.append(current_node.value) | |
current_node = current_node.next_node | |
return ",".join(map(str, values)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment