A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. In simple words, a linked list consists of nodes where each node contains a data field and a reference(link) to the next node in the list.
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
class LinkedList:
head = None
def add(self, val):
node = Node(val)
if self.head is None:
self.head = node
return
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = node
def show(self):
current_node = self.head
while current_node is not None:
print(current_node.val)
current_node = current_node.next
def pop(self):
current_node = self.head
if current_node is None:
raise Exception("LinkedList is empty")
if current_node.next is None:
self.head = None
return
while current_node.next.next is not None:
current_node = current_node.next
current_node.next = None
def delete_at(self, pos):
current_node = self.head
count = 1
if current_node is None:
raise Exception("LinkedList is empty")
if pos == 1:
self.head = current_node.next
while count < pos-1:
if current_node.next is None:
raise Exception("LinkedList index out of bound")
current_node = current_node.next
count += 1
current_node.next = current_node.next.next
def add_at(self, pos, val):
node = Node(val)
current_node = self.head
count = 1
if current_node is None and pos == 1:
self.head = node
return
elif current_node is None:
raise Exception("LinkedList is empty. Try to give position as 1.")
if pos == 1:
node.next = self.head
self.head = node
return
while count < pos-1:
if current_node.next is None:
raise Exception("LinkedList index out of bound")
current_node = current_node.next
count += 1
node.next = current_node.next
current_node.next = node
ll = LinkedList()
ll.add(1)
# ll.add(2)
# ll.add(3)
# ll.add(4)
# ll.add(5)
# ll.show()
# ll.pop()
# ll.show()
# ll.delete_at(100)
ll.add_at(1,10)
ll.show()
Comments
Post a Comment