{"id":26671,"date":"2017-12-22T20:02:11","date_gmt":"2017-12-22T14:32:11","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26671"},"modified":"2017-12-22T20:02:11","modified_gmt":"2017-12-22T14:32:11","slug":"c-programming-inserting-node-linked-list","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-programming-inserting-node-linked-list\/","title":{"rendered":"C 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>C Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ A linked list node<br\/>struct node<br\/>{<br\/>  int data;<br\/>  struct node *next;<br\/>};<\/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>C Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/* Given a reference (pointer to pointer) to the head of a list<br\/>   and an int,  inserts a new node on the front of the list. *\/<br\/>void push(struct node** head_ref, int new_data)<br\/>{<br\/>    \/* 1. allocate node *\/<br\/>    struct node* new_node = (struct node*) malloc(sizeof(struct node));<br\/>  <br\/>    \/* 2. put in the data  *\/<br\/>    new_node-&gt;data  = new_data;<br\/>  <br\/>    \/* 3. Make next of new node as head *\/<br\/>    new_node-&gt;next = (*head_ref);<br\/>  <br\/>    \/* 4. move the head to point to the new node *\/<br\/>    (*head_ref)    = new_node;<br\/>}<\/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>C Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/* Given a node prev_node, insert a new node after the given<br\/>   prev_node *\/<br\/>void insertAfter(struct node* prev_node, int new_data)<br\/>{<br\/>    \/*1. check if the given prev_node is NULL *\/<br\/>    if (prev_node == NULL) <br\/>    { <br\/>       printf(&quot;the given previous node cannot be NULL&quot;);       <br\/>       return;  <br\/>    }  <br\/>          <br\/>    \/* 2. allocate new node *\/<br\/>    struct node* new_node =(struct node*) malloc(sizeof(struct node));<br\/>  <br\/>    \/* 3. put in the data  *\/<br\/>    new_node-&gt;data  = new_data;<br\/>  <br\/>    \/* 4. Make next of new node as next of prev_node *\/<br\/>    new_node-&gt;next = prev_node-&gt;next; <br\/>  <br\/>    \/* 5. move the next of prev_node as new_node *\/<br\/>    prev_node-&gt;next = new_node;<br\/>}<\/code><\/pre> <\/div>\n<p>Time complexity of insertAfter() is O(1) as it does constant amount of work.<\/p>\n[ad type=&#8221;banner&#8221;]\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>C Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/* Given a reference (pointer to pointer) to the head<br\/>   of a list and an int, appends a new node at the end  *\/<br\/>void append(struct node** head_ref, int new_data)<br\/>{<br\/>    \/* 1. allocate node *\/<br\/>    struct node* new_node = (struct node*) malloc(sizeof(struct node));<br\/> <br\/>    struct node *last = *head_ref;  \/* used in step 5*\/<br\/>  <br\/>    \/* 2. put in the data  *\/<br\/>    new_node-&gt;data  = new_data;<br\/> <br\/>    \/* 3. This new node is going to be the last node, so make next <br\/>          of it as NULL*\/<br\/>    new_node-&gt;next = NULL;<br\/> <br\/>    \/* 4. If the Linked List is empty, then make the new node as head *\/<br\/>    if (*head_ref == NULL)<br\/>    {<br\/>       *head_ref = new_node;<br\/>       return;<br\/>    }  <br\/>      <br\/>    \/* 5. Else traverse till the last node *\/<br\/>    while (last-&gt;next != NULL)<br\/>        last = last-&gt;next;<br\/>  <br\/>    \/* 6. Change the next of last node *\/<br\/>    last-&gt;next = new_node;<br\/>    return;    <br\/>}<\/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>C Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ A complete working C program to demonstrate all insertion methods<br\/>\/\/ on Linked List<br\/>#include &lt;stdio.h&gt;<br\/>#include &lt;stdlib.h&gt;<br\/> <br\/>\/\/ A linked list node<br\/>struct node<br\/>{<br\/>  int data;<br\/>  struct node *next;<br\/>};<br\/> <br\/>\/* Given a reference (pointer to pointer) to the head of a list and <br\/>   an int, inserts a new node on the front of the list. *\/<br\/>void push(struct node** head_ref, int new_data)<br\/>{<br\/>    \/* 1. allocate node *\/<br\/>    struct node* new_node = (struct node*) malloc(sizeof(struct node));<br\/> <br\/>    \/* 2. put in the data  *\/<br\/>    new_node-&gt;data  = new_data;<br\/> <br\/>    \/* 3. Make next of new node as head *\/<br\/>    new_node-&gt;next = (*head_ref);<br\/> <br\/>    \/* 4. move the head to point to the new node *\/<br\/>    (*head_ref)    = new_node;<br\/>}<br\/> <br\/>\/* Given a node prev_node, insert a new node after the given <br\/>   prev_node *\/<br\/>void insertAfter(struct node* prev_node, int new_data)<br\/>{<br\/>    \/*1. check if the given prev_node is NULL *\/<br\/>    if (prev_node == NULL)<br\/>    {<br\/>      printf(&quot;the given previous node cannot be NULL&quot;);<br\/>      return;<br\/>    }<br\/> <br\/>    \/* 2. allocate new node *\/<br\/>    struct node* new_node =(struct node*) malloc(sizeof(struct node));<br\/> <br\/>    \/* 3. put in the data  *\/<br\/>    new_node-&gt;data  = new_data;<br\/> <br\/>    \/* 4. Make next of new node as next of prev_node *\/<br\/>    new_node-&gt;next = prev_node-&gt;next;<br\/> <br\/>    \/* 5. move the next of prev_node as new_node *\/<br\/>    prev_node-&gt;next = new_node;<br\/>}<br\/> <br\/>\/* Given a reference (pointer to pointer) to the head<br\/>   of a list and an int, appends a new node at the end  *\/<br\/>void append(struct node** head_ref, int new_data)<br\/>{<br\/>    \/* 1. allocate node *\/<br\/>    struct node* new_node = (struct node*) malloc(sizeof(struct node));<br\/> <br\/>    struct node *last = *head_ref;  \/* used in step 5*\/<br\/> <br\/>    \/* 2. put in the data  *\/<br\/>    new_node-&gt;data  = new_data;<br\/> <br\/>    \/* 3. This new node is going to be the last node, so make next of<br\/>          it as NULL*\/<br\/>    new_node-&gt;next = NULL;<br\/> <br\/>    \/* 4. If the Linked List is empty, then make the new node as head *\/<br\/>    if (*head_ref == NULL)<br\/>    {<br\/>       *head_ref = new_node;<br\/>       return;<br\/>    }<br\/> <br\/>    \/* 5. Else traverse till the last node *\/<br\/>    while (last-&gt;next != NULL)<br\/>        last = last-&gt;next;<br\/> <br\/>    \/* 6. Change the next of last node *\/<br\/>    last-&gt;next = new_node;<br\/>    return;<br\/>}<br\/> <br\/>\/\/ This function prints contents of linked list starting from head<br\/>void printList(struct node *node)<br\/>{<br\/>  while (node != NULL)<br\/>  {<br\/>     printf(&quot; %d &quot;, node-&gt;data);<br\/>     node = node-&gt;next;<br\/>  }<br\/>}<br\/> <br\/>\/* Driver program to test above functions*\/<br\/>int main()<br\/>{<br\/>  \/* Start with the empty list *\/<br\/>  struct node* head = NULL;<br\/> <br\/>  \/\/ Insert 6.  So linked list becomes 6-&gt;NULL<br\/>  append(&amp;head, 6);<br\/> <br\/>  \/\/ Insert 7 at the beginning. So linked list becomes 7-&gt;6-&gt;NULL<br\/>  push(&amp;head, 7);<br\/> <br\/>  \/\/ Insert 1 at the beginning. So linked list becomes 1-&gt;7-&gt;6-&gt;NULL<br\/>  push(&amp;head, 1);<br\/> <br\/>  \/\/ Insert 4 at the end. So linked list becomes 1-&gt;7-&gt;6-&gt;4-&gt;NULL<br\/>  append(&amp;head, 4);<br\/> <br\/>  \/\/ Insert 8, after 7. So linked list becomes 1-&gt;7-&gt;8-&gt;6-&gt;4-&gt;NULL<br\/>  insertAfter(head-&gt;next, 8);<br\/> <br\/>  printf(&quot;\\n Created Linked list is: &quot;);<br\/>  printList(head);<br\/> <br\/>  return 0;<br\/>}<\/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>C Programming -Time complexity of append is O(n) where n is number of nodes in linked list. Since there is a 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":[69866,1,79476,79478],"tags":[79729,2870,79728,79721,79723,79720,79724,2874,79719,79726,79727,79725,79722,2869,79730],"class_list":["post-26671","post","type-post","status-publish","format-standard","hentry","category-c-programming","category-coding","category-linked-list","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\/26671","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=26671"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26671\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26671"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26671"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26671"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}