{"id":26716,"date":"2017-12-22T20:08:01","date_gmt":"2017-12-22T14:38:01","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26716"},"modified":"2017-12-22T20:08:01","modified_gmt":"2017-12-22T14:38:01","slug":"python-programming-inserting-node-linked-list","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-programming-inserting-node-linked-list\/","title":{"rendered":"Python Programming &#8211; Inserting a node in Linked List | Set 2"},"content":{"rendered":"<p>We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.<span id=\"more-142784\"><\/span><\/p>\n<p>All programs discussed in this post consider following representations of linked list<\/p>\n<p><strong>Python Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Node class<br\/>class Node:<br\/> <br\/>    # Function to initialize the node object<br\/>    def __init__(self, data):<br\/>        self.data = data  # Assign data<br\/>        self.next = None  # Initialize next as null<br\/> <br\/># Linked List class<br\/>class LinkedList:<br\/>   <br\/>    # Function to initialize the Linked List object<br\/>    def __init__(self): <br\/>        self.head = None<\/code><\/pre> <\/div>\n<p>In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways<br \/>\n<strong>1)<\/strong> At the front of the linked list<br \/>\n<strong>2) <\/strong>After a given node.<br \/>\n<strong>3)<\/strong> At the end of the linked list.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Add a node at the front: (A 4 steps process)<\/strong><br \/>\nThe new node is always added before the head of the given Linked List. And newly added node becomes the new head of the Linked List. For example if the given Linked List is 10-&gt;15-&gt;20-&gt;25 and we add an item 5 at the front, then the Linked List becomes 5-&gt;10-&gt;15-&gt;20-&gt;25. Let us call the function that adds at the front of the list is push(). The push() must receive a pointer to the head pointer, because push must change the head pointer to point to the new node (See this)<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"alignleft size-full wp-image-26695\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linkedlist_insert_at_start.png\" alt=\"C Algorithm - Inserting a node in Linked List | Set 2\" width=\"759\" height=\"255\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linkedlist_insert_at_start.png 759w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linkedlist_insert_at_start-300x101.png 300w\" sizes=\"(max-width: 759px) 100vw, 759px\" \/><\/p>\n<p>Following are the 4 steps to add node at the front.<\/p>\n<p><strong>Python Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># This function is in LinkedList class<br\/># Function to insert a new node at the beginning<br\/>def push(self, new_data):<br\/> <br\/>    # 1 &amp; 2: Allocate the Node &amp;<br\/>    #        Put in the data<br\/>    new_node = Node(new_data)<br\/>         <br\/>    # 3. Make next of new Node as head<br\/>    new_node.next = self.head<br\/>         <br\/>    # 4. Move the head to point to new Node <br\/>    self.head = new_node<\/code><\/pre> <\/div>\n<p>Time complexity of push() is O(1) as it does constant amount of work.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Add a node after a given node: (5 steps process)<\/strong><br \/>\nWe are given pointer to a node, and the new node is inserted after the given node.<\/p>\n<p><img decoding=\"async\" class=\"alignleft size-full wp-image-26698\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linkedlist_insert_middle.png\" alt=\"C Programming - Inserting a node in Linked List | Set 2\" width=\"759\" height=\"273\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linkedlist_insert_middle.png 759w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linkedlist_insert_middle-300x108.png 300w\" sizes=\"(max-width: 759px) 100vw, 759px\" \/><br \/>\n<strong>Python Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># This function is in LinkedList class.<br\/># Inserts a new node after the given prev_node. This method is <br\/># defined inside LinkedList class shown above *\/<br\/>def insertAfter(self, prev_node, new_data):<br\/> <br\/>    # 1. check if the given prev_node exists<br\/>    if prev_node is None:<br\/>        print &quot;The given previous node must inLinkedList.&quot;<br\/>        return<br\/> <br\/>    #  2. Create new node &amp;<br\/>    #  3. Put in the data<br\/>    new_node = Node(new_data)<br\/> <br\/>    # 4. Make next of new Node as next of prev_node <br\/>    new_node.next = prev_node.next<br\/> <br\/>    # 5. make next of prev_node as new_node <br\/>    prev_node.next = new_node<\/code><\/pre> <\/div>\n<p>Time complexity of insertAfter() is O(1) as it does constant amount of work.<\/p>\n<p><strong>Add a node at the end: (6 steps process)<\/strong><br \/>\nThe new node is always added after the last node of the given Linked List. For example if the given Linked List is 5-&gt;10-&gt;15-&gt;20-&gt;25 and we add an item 30 at the end, then the Linked List becomes 5-&gt;10-&gt;15-&gt;20-&gt;25-&gt;30.<br \/>\nSince a Linked List is typically represented by the head of it, we have to traverse the list till end and then change the next of last node to new node.<\/p>\n<p><img decoding=\"async\" class=\"alignleft size-full wp-image-26703\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linkedlist_insert_last.png\" alt=\"C Programming - Inserting a node in Linked List | Set 2\" width=\"759\" height=\"245\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linkedlist_insert_last.png 759w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linkedlist_insert_last-300x97.png 300w\" sizes=\"(max-width: 759px) 100vw, 759px\" \/><\/p>\n<p>Following are the 6 steps to add node at the end<\/p>\n<p><strong>Python Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># This function is defined in Linked List class<br\/># Appends a new node at the end.  This method is<br\/>#  defined inside LinkedList class shown above *\/<br\/>def append(self, new_data):<br\/> <br\/>   # 1. Create a new node<br\/>   # 2. Put in the data<br\/>   # 3. Set next as None<br\/>   new_node = Node(new_data)<br\/> <br\/>   # 4. If the Linked List is empty, then make the<br\/>   #    new node as head<br\/>   if self.head is None:<br\/>        self.head = new_node<br\/>        return<br\/> <br\/>   # 5. Else traverse till the last node<br\/>   last = self.head<br\/>   while (last.next):<br\/>       last = last.next<br\/> <br\/>   # 6. Change the next of last node<br\/>   last.next =  new_node<\/code><\/pre> <\/div>\n<p>Time complexity of append is O(n) where n is the number of nodes in linked list. Since there is a loop from head to end, the function does O(n) work.<br \/>\nThis method can also be optimized to work in O(1) by keeping an extra pointer to tail of linked list<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Following is a complete program that uses all of the above methods to create a linked list.<\/strong><\/p>\n<p><strong>Python Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># A complete working Python program to demonstrate all<br\/># insertion methods of linked list<br\/> <br\/># Node class<br\/>class Node:<br\/> <br\/>    # Function to initialise the node object<br\/>    def __init__(self, data):<br\/>        self.data = data  # Assign data<br\/>        self.next = None  # Initialize next as null<br\/> <br\/> <br\/># Linked List class contains a Node object<br\/>class LinkedList:<br\/> <br\/>    # Function to initialize head<br\/>    def __init__(self):<br\/>        self.head = None<br\/> <br\/> <br\/>    # Functio to insert a new node at the beginning<br\/>    def push(self, new_data):<br\/> <br\/>        # 1 &amp; 2: Allocate the Node &amp;<br\/>        #        Put in the data<br\/>        new_node = Node(new_data)<br\/> <br\/>        # 3. Make next of new Node as head<br\/>        new_node.next = self.head<br\/> <br\/>        # 4. Move the head to point to new Node<br\/>        self.head = new_node<br\/> <br\/> <br\/>    # This function is in LinkedList class. Inserts a<br\/>    # new node after the given prev_node. This method is<br\/>    # defined inside LinkedList class shown above *\/<br\/>    def insertAfter(self, prev_node, new_data):<br\/> <br\/>        # 1. check if the given prev_node exists<br\/>        if prev_node is None:<br\/>            print &quot;The given previous node must inLinkedList.&quot;<br\/>            return<br\/> <br\/>        #  2. create new node &amp;<br\/>        #      Put in the data<br\/>        new_node = Node(new_data)<br\/> <br\/>        # 4. Make next of new Node as next of prev_node<br\/>        new_node.next = prev_node.next<br\/> <br\/>        # 5. make next of prev_node as new_node<br\/>        prev_node.next = new_node<br\/> <br\/> <br\/>    # This function is defined in Linked List class<br\/>    # Appends a new node at the end.  This method is<br\/>    # defined inside LinkedList class shown above *\/<br\/>    def append(self, new_data):<br\/> <br\/>        # 1. Create a new node<br\/>        # 2. Put in the data<br\/>        # 3. Set next as None<br\/>        new_node = Node(new_data)<br\/> <br\/>        # 4. If the Linked List is empty, then make the<br\/>        #    new node as head<br\/>        if self.head is None:<br\/>            self.head = new_node<br\/>            return<br\/> <br\/>        # 5. Else traverse till the last node<br\/>        last = self.head<br\/>        while (last.next):<br\/>            last = last.next<br\/> <br\/>        # 6. Change the next of last node<br\/>        last.next =  new_node<br\/> <br\/> <br\/>    # Utility function to print the linked list<br\/>    def printList(self):<br\/>        temp = self.head<br\/>        while (temp):<br\/>            print temp.data,<br\/>            temp = temp.next<br\/> <br\/> <br\/> <br\/># Code execution starts here<br\/>if __name__==&#039;__main__&#039;:<br\/> <br\/>    # Start with the empty list<br\/>    llist = LinkedList()<br\/> <br\/>    # Insert 6.  So linked list becomes 6-&gt;None<br\/>    llist.append(6)<br\/> <br\/>    # Insert 7 at the beginning. So linked list becomes 7-&gt;6-&gt;None<br\/>    llist.push(7);<br\/> <br\/>    # Insert 1 at the beginning. So linked list becomes 1-&gt;7-&gt;6-&gt;None<br\/>    llist.push(1);<br\/> <br\/>    # Insert 4 at the end. So linked list becomes 1-&gt;7-&gt;6-&gt;4-&gt;None<br\/>    llist.append(4)<br\/> <br\/>    # Insert 8, after 7. So linked list becomes 1 -&gt; 7-&gt; 8-&gt; 6-&gt; 4-&gt; None<br\/>    llist.insertAfter(llist.head.next, 8)<br\/> <br\/>    print &#039;Created linked list is:&#039;,<br\/>    llist.printList()<br\/> <br\/># This code is contributed by Manikantan Narasimhan<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre> Created Linked list is:  1  7  8  6  4<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Python Programming &#8211; Time complexity of append &#8211; O(n) where n is number of nodes in linked list. Since there is loop from head to end the function does O(n) <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,79476,4148,79478],"tags":[79729,2870,79728,79721,79723,79720,79724,2874,79719,79726,79727,79725,79722,2869,79730],"class_list":["post-26716","post","type-post","status-publish","format-standard","hentry","category-coding","category-linked-list","category-python","category-singly-linked-list","tag-advantages-and-disadvantages-of-linked-list-over-array","tag-arraylist-vs-linkedlist-c","tag-difference-between-array-and-linked-list-in-data-structure","tag-difference-between-array-and-linked-list-in-java","tag-difference-between-array-and-linked-list-ppt","tag-difference-between-array-and-linked-list-wikipedia","tag-difference-between-array-and-stack","tag-difference-between-arraylist-and-array","tag-difference-between-arraylist-and-linked-list","tag-difference-between-arraylist-and-linkedlist-and-vector-in-java","tag-difference-between-arraylist-and-vector","tag-difference-between-singly-linked-list-and-doubly-linked-list","tag-linked-list-vs-array-performance","tag-what-is-doubly-linked-list-in-java","tag-what-is-the-difference-between-hashset-and-hashmap-classes-in-collection-framework"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26716","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26716"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26716\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26716"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26716"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26716"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}