class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_at_start(self, val):
new_node = Node(val) # create new node
new_node.next = self.head # point new node to current head
self.head = new_node # update head to new node
def print_list(self):
curr = self.head
result = []
while curr:
result.append(str(curr.val))
curr = curr.next
print('Head -> ' + ' -> '.join(result) + ' -> null')
# Array insert simulation
arr = [1, 2, 3]
# Insert 0 at start by shifting
arr = [0] + arr # shifting all elements right
print('Array after insert:', arr)
# Linked list insert
ll = LinkedList()
for v in reversed([1, 2, 3]):
ll.insert_at_start(v)
ll.insert_at_start(0) # insert 0 at start
print('Linked list after insert:')
ll.print_list()new_node = Node(val) # create new node
create a new node to hold the value
new_node.next = self.head # point new node to current head
link new node to the current first node
self.head = new_node # update head to new node
make new node the first node in the list
arr = [0] + arr # shifting all elements right
simulate array insert by creating new array with 0 at front
Array after insert: [0, 1, 2, 3]
Linked list after insert:
Head -> 0 -> 1 -> 2 -> 3 -> null