position: fixed; top: auto !important; margin-left: 112px;

Linked List Insertion at the end a given node

Linked List insertion can be done using three ways,

1) Insertion at front of given node.

2) Insertion after a given node.

3) Insertion at the end of node.

In this tutorial we consider insertion at front of given node . To understand this look at following figure ,

1) Before Scenario : Insertion at the end a given node.

1) Original Linked list contains a head pointer pointing to First Node.

2) First Node points to second Node containing value 2.

3) Second Node points to third node containing value 3 .

4) Third Node points to NULL .


2) After Scenario : Insertion at the end of a given node.

Now if we want to insert node at the end of a given node of linked list , it should be like,

1) Head is pointing to first Node containing value 1.

2) First Node points to second Node containing value 2.

3) Second Node points to third node containing value 3 .

4) New Node's next points to NULL.

5) Third node's next points to New Node.


Playing with linked list is very easy task . Just you should know which node will points to which node. This was the beginning of linked list insertion.

Function to insert node after a given node of Linked List :

void insertNodeAtend(struct node** head_ref, int new_data)
{
  /* 1. allocate node */
    struct node* new_node = (struct node*) malloc(sizeof(struct node));
 
    struct node *last = *head_ref;  /* used in step 5*/
  
  /* 2. put in the data  */
    new_node->data  = new_data;
 
  /* 3. This new node is going to be the last node, so make next 
          of it as NULL*/ 
    new_node->next = NULL;
 
  /* 4. If the Linked List is empty, then make the new node as head */
    if (*head_ref == NULL)
    {
       *head_ref = new_node;
       return;
    }  
      
  /* 5. Else traverse till the last node */
    while (last->next != NULL)
        last = last->next;
  
  /* 6. Change the next of last node */
    last->next = new_node;
    return;    
}

Solve the Quiz of Article

1) While implementing the bubble sort algorithm, what do you think algorithm needs n - 1 comparison in Pass 1?
Yes
No

2) What do you think best case performance of Bubble Sort Algorithms is O(n2)?
Yes
No


Previous Next Article







codzify.com


Largest collection of up-to-date tutorials to learn programming languages. We are focused on easy learning. Massive collection of interview questions one may need for preparation.

Social Profile


Linkedin
Twitter
Facebook

Copyright 2018. All rights reserved.