If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Sure! Let's create a linked list by inserting elements at the end of the list. To achieve this, we'll modify the
appendmethod to perform the insertion.
pythonCopy code
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self, data): new_node = Node(data) if not self.head: self.head = new_node else: current = self.head while current.next: current = current.next current.next = 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.append(3) linked_list.append(7) linked_list.append(1) linked_list.append(9) # Display the linked list print("Linked List:") linked_list.display()In this example, we define the
NodeandLinkedListclasses. TheLinkedListclass has anappendmethod that inserts elements at the end of the linked list. We then create a linked list object, and using theappendmethod, we add elements (3, 7, 1, and 9) to create the linked list. Finally, we display the created linked list.The output will be:
rustCopy code
Linked List: 3 -> 7 -> 1 -> 9 -> NoneThe linked list is created with elements inserted at the end, resulting in the order 3 -> 7 -> 1 -> 9.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support