Group_Coder

Inserting a node at a specific position

Jul 26th, 2023
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. class Node:
  2. def __init__(self, data):
  3. self.data = data
  4. self.next = None
  5.  
  6. class LinkedList:
  7. def __init__(self):
  8. self.head = None
  9.  
  10. def add_node_to_front(self, data):
  11. new_node = Node(data)
  12. new_node.next = self.head
  13. self.head = new_node
  14.  
  15. def add_node_to_end(self, data):
  16. new_node = Node(data)
  17. if not self.head:
  18. self.head = new_node
  19. return
  20.  
  21. current = self.head
  22. while current.next:
  23. current = current.next
  24.  
  25. current.next = new_node
  26.  
  27. def remove_node(self, target_data):
  28. if not self.head:
  29. return
  30.  
  31. if self.head.data == target_data:
  32. self.head = self.head.next
  33. return
  34.  
  35. current = self.head
  36. while current.next:
  37. if current.next.data == target_data:
  38. current.next = current.next.next
  39. return
  40. current = current.next
  41.  
  42. def print_linked_list(self):
  43. current = self.head
  44. while current:
  45. print(current.data, end=" -> ")
  46. current = current.next
  47. print("None")
  48.  
  49. def length(self):
  50. count = 0
  51. current = self.head
  52. while current:
  53. count += 1
  54. current = current.next
  55. return count
  56.  
  57. def search(self, target_data):
  58. current = self.head
  59. while current:
  60. if current.data == target_data:
  61. return True
  62. current = current.next
  63. return False
  64.  
  65. def insert_at_position(self, data, position):
  66. if position == 0 or not self.head:
  67. self.add_node_to_front(data)
  68. return
  69.  
  70. new_node = Node(data)
  71. current = self.head
  72. for _ in range(position - 1):
  73. if not current.next:
  74. break
  75. current = current.next
  76.  
  77. new_node.next = current.next
  78. current.next = new_node
  79.  
  80. # Creating a linked list
  81. my_linked_list = LinkedList()
  82.  
  83. # Adding nodes to the front of the linked list
  84. my_linked_list.add_node_to_front("World")
  85. my_linked_list.add_node_to_front("Hello")
  86.  
  87. # Adding nodes to the end of the linked list
  88. my_linked_list.add_node_to_end("!")
  89. my_linked_list.add_node_to_end("Goodbye")
  90.  
  91. # Inserting a node at a specific position
  92. my_linked_list.insert_at_position("Python", 1)
  93.  
  94. # Printing the linked list
  95. my_linked_list.print_linked_list()
  96.  
Advertisement
Add Comment
Please, Sign In to add comment