Created
February 24, 2021 13:34
-
-
Save alejolp/4e6576ab34dcb3986623c5f2f7b9b0ae to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ListNode: | |
def __init__(self, value, next): | |
self.value = value | |
self.next = next | |
class LinkedList: | |
def __init__(self): | |
self.head = None | |
def print_list_values(the_list): | |
aux = the_list.head | |
while aux != None: | |
print(aux.value) | |
aux = aux.next | |
def insert_at_end(the_list, the_node): | |
# Two pointers, previous pointer and aux pointer | |
prev = None | |
aux = the_list.head | |
while aux != None: | |
prev = aux | |
aux = aux.next | |
if prev == None: | |
the_list.head = the_node | |
else: | |
prev.next = the_node | |
def insert_at_beginning(the_list, the_node): | |
the_node.next = the_list.head | |
the_list.head = the_node | |
def insert_at_pos(the_list, the_node, pos): | |
prev = None | |
aux = the_list.head | |
idx = 0 | |
while aux != None and idx < pos: | |
prev = aux | |
aux = aux.next | |
idx = idx + 1 | |
if prev == None: | |
the_list.head = the_node | |
else: | |
prev.next = the_node | |
the_node.next = aux | |
def remove_beginning(the_list): | |
aux = the_list.head | |
the_list.head = aux.next | |
return aux | |
def remove_end(the_list): | |
aux = the_list.head | |
prev = None | |
while aux.next != None: | |
prev = aux | |
aux = aux.next | |
if prev == None: | |
result = the_list.head | |
the_list.head = None | |
else: | |
result = prev.next | |
prev.next = None | |
return result | |
my_new_list = LinkedList() | |
new_node1 = ListNode(42, None) | |
new_node2 = ListNode(64, None) | |
new_node3 = ListNode(99, None) | |
new_node4 = ListNode(23, None) | |
insert_at_end(my_new_list, new_node1) | |
insert_at_end(my_new_list, new_node2) | |
insert_at_beginning(my_new_list, new_node3) | |
insert_at_pos(my_new_list, new_node4, 1) | |
print_list_values(my_new_list) | |
remove_beginning(my_new_list) | |
remove_end(my_new_list) | |
print() | |
print_list_values(my_new_list) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment