If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Sure! We can create a linked list by using the
insert
method to add elements to the list one by one. Below is an example of how you can create a linked list using insertions:
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def insert(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def display(self): current = self.head while current: print(current.data, end=" -> ") current = current.next print("None") # Example usage: if __name__ == "__main__": linked_list = LinkedList() # Insert elements to create the linked list linked_list.insert(3) linked_list.insert(7) linked_list.insert(1) linked_list.insert(9) # Display the linked list print("Linked List:") linked_list.display()
In this example, we first define the
Node
andLinkedList
classes. TheLinkedList
class has aninsert
method that inserts elements at the beginning of the linked list. We then create a linked list object, and using theinsert
method, we add elements (3, 7, 1, and 9) to create the linked list. Finally, we display the created linked list.The output will be:
rust
Copy code
Linked List: 9 -> 1 -> 7 -> 3 -> None
The linked list is created in reverse order due to inserting elements at the beginning, resulting in the order 9 -> 1 -> 7 -> 3.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform