Advertisement
AyanUpadhaya

Intro to Data Structure Single Linked List

Jul 22nd, 2021
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.44 KB | None | 0 0
  1. # First we need a node class, why?
  2. # node will contain a value and it will know what is the next value
  3. # but by default both can be none
  4.  
  5. # Now we will need a single linked list class,why?
  6. # It will contain every node in order, how?
  7. # it will have a head which is default None and will be updated
  8. # it will be able show us all nodes
  9. # it will be able to update the head
  10.  
  11.  
  12. class Node:
  13.     def __init__(self,data=None):
  14.         self.data = data
  15.         self.next = None
  16.  
  17. class Single_Linked_List:
  18.     def __init__(self):
  19.         self. head = None
  20.  
  21.     #method for showing all nodes
  22.     def showNodes(self):
  23.         mainval = self.head
  24.  
  25.         while mainval is not None:
  26.             print(mainval.data)
  27.             mainval = mainval.next
  28.  
  29.     def updateHead(self,new_data):
  30.         new_node = Node(new_data)
  31.         new_node.next = self.head #head will be second item
  32.         self.head = new_node
  33.  
  34. list1 = Single_Linked_List()
  35. list1.head = Node('4')
  36.  
  37. list2 = Node('5')
  38. list3 = Node('6')
  39. list4 = Node('7')
  40.  
  41. #connecting the nodes
  42.  
  43. list1.head.next = list2
  44. list2.next = list3
  45. list3.next = list4
  46.  
  47. list1.updateHead('3')
  48.  
  49. list1.showNodes()
  50.  
  51.  
  52. # So how single link list is working?
  53. # single link list has a head which is node itself
  54. # we can create new node and assign it as the next node for head
  55. # so every node will know what is the next node, which means we have to connect it
  56. # head can be modified which means current head will be second node of the new node and
  57. # new node will take place as the head
  58.  
  59.  
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement