Singly Linked List Implementation


DS Intro.png

1.Node Class.png

2. Linked List Class.png

3. Insert at Beginning.png

4. Insert at End.png

5. Insert after Node .png

6. Delete at Beginning.png

7. Delete at End.png

8. Delete Node .png

9. Print List .png

Example.png

PYTHON CODE

class Node:
  
  def __init__(self,data):
    self.data = data
    self.next = None  #Initially, each node points to None
    
    
    
class LinkedList:
  
  def __init__(self):
    self.head = None  #The head points to the first node (or None if empty)
    
    
  def insert_at_beginning(self,data):
    new_node = Node(data)
    new_node.next = self.head   # The new node's next points to the old head
    self.head = new_node    # Update the head to the new node
    
  
  def insert_at_end(self,data):
    new_node = Node(data)
    if self.head is None:
      self.head = new_node
      return
      
    last_node = self.head
    while last_node.next:
      last_node = last_node.next
    last_node.next = new_node
    
  
  def insert_after_node(self,prev_node,data):
    if prev_node is None:
      print("The given previous node cannot be None")
      return
    
    new_node = Node(data)
    new_node.next = prev_node.next    # Update the head to the new node
    prev_node.next = new_node     # Connect the previous node to the new node
    
    
  def delete_at_beginning(self):
    if self.head is None:
      return
    
    self.head = self.head.next    # Move the head to the next node, effectively deleting the first
    
  
  def delete_at_end(self):
    if self.head is None:
      return
    
    if self.head.next is None:
      self.head = None
      return
    
    last_node = self.head
    while last_node.next.next:
      last_node = last_node.next
      
    last_node.next =None
    
  
  def delete_node(self,key):
    temp = self.head
    prev = None
    
    if temp is not None and temp.data == key:
      self.head = temp.next   # Update the head if the key is at the beginning
      temp = None
      return
    
    while temp is not None and temp.data != key:
      prev = temp
      temp = temp.next
      
    if temp is None:
      return    # Key not found
    
    prev.next = temp.next   # Bypass the node to be deleted
    
    
  def print_list(self):
    temp = self.head
    
    while temp:
      print(temp.data,end= ' ')
      temp = temp.next
    print( )
    
    
    
    
llist = LinkedList()
llist.insert_at_beginning(15)
llist.insert_at_beginning(10)
llist.insert_at_beginning(5)
llist.insert_at_end(25)
llist.insert_at_end(30)
llist.insert_at_end(35)
llist.insert_after_node(llist.head.next.next,20)
llist.insert_after_node(llist.head.next.next.next,22)
llist.delete_at_beginning()
llist.delete_at_end()
llist.delete_node(22)
llist.print_list()