rosien

linkedlist

Jul 1st, 2020
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Node class
  2. class Node:
  3.  
  4.     # Function to initialize the node object
  5.     def __init__(self, data):
  6.         self.data = data # Assign data
  7.         self.next = None # Initialize next as null
  8.  
  9. # Linked List class
  10. class LinkedList:
  11.    
  12.     # Function to initialize the Linked List object
  13.     def __init__(self):
  14.         self.head = None
  15.     def print_linkedlist(self):
  16.         nodes = []
  17.         node = self.head
  18.         while node:
  19.             nodes.append(node.data)
  20.             node = node.next
  21.         nodes.append('None')
  22.         print('->'.join(nodes))
  23.  
  24. one = Node("1")
  25. two = Node('2')
  26. three = Node('3')
  27. llist = LinkedList()
  28. llist.head = one
  29. one.next = two
  30. two.next = three
  31.  
  32. def push(self, new_data):
  33.  
  34.     # 1 & 2: Allocate the Node &
  35.     #    Put in the data
  36.     new_node = Node(new_data)
  37.        
  38.     # 3. Make next of new Node as head
  39.     new_node.next = self.head
  40.        
  41.     # 4. Move the head to point to new Node
  42.     self.head = new_node
  43.  
  44. def insertLast(self, new_data):
  45.     #create a new node
  46.     new_node = Node(new_data)
  47.    
  48.     #if linkedlist is empty, make the new node as head
  49.     if self.head is None:
  50.         self.head = new_node
  51.         return
  52.     #else traverse till the last node
  53.     last = self.head
  54.     while (last.next):
  55.         last = last.next
  56.        
  57.     #change the next of last node
  58.     last.next = new_node
  59.  
  60.  
  61. def del_node(self, data_to_del):
  62.     #store head node
  63.     node = self.head
  64.    
  65.     #if head node itself hold the key to be deleted
  66.     if node is not None:
  67.         if node.data== data_to_del:
  68.             self.head = node.next
  69.             node = None
  70.             return
  71.    
  72.     # search for the data to be deleted, keep track of
  73.     # the prev_node as we need to change 'prev.next'
  74.    
  75.     while node is not None:
  76.         if node.data ==data_to_del:
  77.             break
  78.         prev_node = node
  79.         node = node.next
  80.    
  81.     #if key was not present in Linked list
  82.     if node == None:
  83.         return
  84.    
  85.     #unlink the node from linked list
  86.     prev_node.next = node.next
  87.     node = None
Add Comment
Please, Sign In to add comment