Friday, October 25, 2024

Singly linked list python

 


# singly linked list

class Node:
  def __init__(self,data):
    self.data = data
    self.next = None

class ll:
  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 show(self):
    current = self.head
    while current:
      if current.data != None:
        print(current.data,'->',end='')
      current = current.next
    print()
 
  def delete(self,value):
    current = self.head
    while current:
      if current.data != None and current.data == value:
        current.data = None
      current = current.next
    print("deleted...")
    self.show()
    self.size()

# if you wish to delete the node and don't want none
    def delete(self,value):
        current = self.head
        while current:
            if current.data == value:
                previous.next = current.next  # Skip over the node to delete it
                current = None  # Optional: free the node
                print(f"Node with value {value} deleted.")
                self.display()
                return
            previous = current
            current = current.next
 
  def update(self,value,replace):
    current = self.head
    while current:
      if current.data != None and current.data == value:
        current.data = replace
      current = current.next
    print("updated...")
    self.show()
   
  def size(self):
    current = self.head
    size=0
    while current:
      if current.data != None :
        size += 1
      current = current.next
    print(f"size is {size}...!")
 
l = ll()
l.insert(1)
l.insert(2)
l.insert(3)
l.insert(4)
l.insert(5)

l.show()

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 ...