Technology and generation are growing up together, and the younger generation users are somewhat connected with tech and the internet all the time. Not to mention, today the whole world in this time of crisis is working over the internet. But to make these technologies, software, etc a software developer must have excellent problem-solving skills. In this world where the internet is the new fuel, one needs to be pretty sharp. And by sharp, for software developers, it means knowing how to automate real-world problems using computer programs. Data structures help a lot in this journey of logic building. So today we’re going to write a simple data structure program to Insert A Node At the End In Linked List using Python.
What is A Linked List?
A linked list is a basic list of nodes containing different elements for all algorithms in data structures. Also, it’s pretty easy to understand.
What’s The Approach?
- Firstly we’ll allocate a new node, by simply creating it.
- Next up we’ll insert the data in this new node.
- Now, the
nextsection of the node is set to null showing the end of the linked list.
- Also,o the
nextsection of our linked list is going to point towards the head of this newly created node.
Also Read: Print Cube Root Of A Number in Java
Python Program To Insert A Node At End In Linked List
Created Linked List is: 7 6
# Python program to demonstrate all # insertion methods of linked list at the end # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node object class LinkedList: # Function to initialize head def __init__(self): self.head = None # Functio to insert a new node at the beginning def push(self, new_data): # 1 & 2: Allocate the Node & # Put in the data new_node = Node(new_data) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node # This function is defined in Linked List class # Appends a new node at the end. def append(self, new_data): # 1. Create a new node # 2. Put in the data # 3. Set next as None new_node = Node(new_data) # 4. If the Linked List is empty, then make the # new node as head if self.head is None: self.head = new_node return # 5. Else traverse till the last node last = self.head while (last.next): last = last.next # 6. Change the next of last node last.next = new_node # Utility function to print the linked list def printList(self): temp = self.head while (temp): print temp.data, temp = temp.next # Driver Code if __name__=='__main__': # Start with the empty list llist = LinkedList() # Insert 6. So linked list becomes 6->None llist.append(6) # Insert 7 at the beginning. So linked list becomes 7->6->None llist.push(7); print 'Created linked list is:', llist.printList()