Thursday, July 3, 2025

singly linked list advanced

 class Node:
  def __init__(self,data):
    self.data = data 
    self.next = None 
class sl:
  def __init__(self):
    self.head = None 
  
  def is_empty(self):
    return self.head is None 
  
  def insert(self,value):
    new_node = Node(value)
    if self.is_empty():
      self.head = new_node
    else:
      new_node.next = self.head 
      self.head = new_node
  
  def insert_at(self,value,new_value):
    new_node = Node(new_value)
    current = self.head 
    while current:
      if current.data == value:
        new_node.next = current.next 
        current.next = new_node
      current = current.next 
    print()
  
  def show(self):
    current = self.head 
    while current:
      print(current.data,'->',end='')
      current = current.next 
    print()
  
  def delete(self,value):
    current = self.head 
    
    if current.data == value:
      self.head.data = None 
      self.head = self.head.next
    while current:
      if current.data == value and current.next != None:
        current.data = current.next.data 
        current.next = current.next.next 
      current = current.next 
    l.show()
    print()
    
l = sl()
for i in range(1,10):
  l.insert(i)
  
l.show()
l.delete(9)
l.delete(1)
l.delete(8)
l.delete(7)
l.delete(6)
l.delete(3)
l.delete(2)

Output:

9 ->8 ->7 ->6 ->5 ->4 ->3 ->2 ->1 ->
8 ->7 ->6 ->5 ->4 ->3 ->2 ->1 ->

8 ->7 ->6 ->5 ->4 ->3 ->2 ->1 ->

7 ->6 ->5 ->4 ->3 ->2 ->1 ->

6 ->5 ->4 ->3 ->2 ->1 ->

5 ->4 ->3 ->2 ->1 ->

5 ->4 ->2 ->1 ->

5 ->4 ->1 ->

No comments:

Post a Comment

virtual environment on python on Ubuntu

 # 1. Update system and install Python tools sudo apt update && sudo apt install python3-pip python3-venv -y # 2. Setup Django in a ...