Insert A Node At Front In Linked List using Python

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 Front 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 the linked list.

 

  • Now, this new node is going to become the head of the linked list.

 

 

Also Read: Print Cube Root Of A Number in Python

 

Python Program To Insert A Node At Front In Linked List

 

Input:

 

push(6)

 

Output:

 

Created Linked List is: 6

 

# Python program to demonstrate
# insertion methods of linked list

# 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

    # Utility function to print the linked list
    def printList(self):
        temp = self.head
        while (temp):
            print temp.data,
            temp = temp.next



# Code execution starts here
if __name__=='__main__':

    # Start with the empty list
    llist = LinkedList()

    # Insert 6. So linked list becomes 6->None
    llist.push(6)

    print 'Created linked list is:',
    llist.printList()

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published.