Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node:
- def __init__(self, data):
- self.data = data
- self.next = None
- class LinkedList:
- def __init__(self):
- self.head = None
- def add_node_to_front(self, data):
- new_node = Node(data)
- new_node.next = self.head
- self.head = new_node
- def add_node_to_end(self, data):
- new_node = Node(data)
- if not self.head:
- self.head = new_node
- return
- current = self.head
- while current.next:
- current = current.next
- current.next = new_node
- def remove_node(self, target_data):
- if not self.head:
- return
- if self.head.data == target_data:
- self.head = self.head.next
- return
- current = self.head
- while current.next:
- if current.next.data == target_data:
- current.next = current.next.next
- return
- current = current.next
- def print_linked_list(self):
- current = self.head
- while current:
- print(current.data, end=" -> ")
- current = current.next
- print("None")
- def length(self):
- count = 0
- current = self.head
- while current:
- count += 1
- current = current.next
- return count
- def search(self, target_data):
- current = self.head
- while current:
- if current.data == target_data:
- return True
- current = current.next
- return False
- def insert_at_position(self, data, position):
- if position == 0 or not self.head:
- self.add_node_to_front(data)
- return
- new_node = Node(data)
- current = self.head
- for _ in range(position - 1):
- if not current.next:
- break
- current = current.next
- new_node.next = current.next
- current.next = new_node
- # Creating a linked list
- my_linked_list = LinkedList()
- # Adding nodes to the front of the linked list
- my_linked_list.add_node_to_front("World")
- my_linked_list.add_node_to_front("Hello")
- # Adding nodes to the end of the linked list
- my_linked_list.add_node_to_end("!")
- my_linked_list.add_node_to_end("Goodbye")
- # Inserting a node at a specific position
- my_linked_list.insert_at_position("Python", 1)
- # Printing the linked list
- my_linked_list.print_linked_list()
Advertisement
Add Comment
Please, Sign In to add comment