Advertisement
sol4r

Singly Linked List | Data Structures

Aug 29th, 2022
948
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. class Node(): #First we will create the nodes which will contain 2 fields (i) data (ii) link/reference
  2.     def __int__(self,data):#initializing the node with 2 fields (i) data (ii) link/reference
  3.         self.data = data
  4.         self.reference = None #for empty value / setting reference as None
  5.  
  6. class LinkedList(): #connecting those nodes
  7.     def __init__(self):
  8.         self.head = None #initializing the head as None / which also means the list is empty or has no nodes in it
  9.  
  10.         #Note Reference of the first node is stored in the head
  11.  
  12.     def viweing_linkedlist(self): #Traversing The LinkedList
  13.         if self.head is None:
  14.             print("Linked list is empty!")
  15.  
  16.         else:
  17.             n = self.head
  18.             while n is not None:
  19.                 print(n.data)
  20.                 n = n.reference
  21.  
  22.     def add_begin(self, data):#Adding in the Linked List
  23.         new_node = Node(data)
  24.         new_node.reference = self.head
  25.         self.head = new_node
  26.  
  27.  
  28.  
  29. #For Reference Refer to
  30. #https://www.youtube.com/watch?v=xRTdfZsAz6Y
  31. #https://www.youtube.com/watch?v=B-zO18TJKYQ
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement