Skip to content
Home » Inserting a node at the end of the single linked list

Inserting a node at the end of the single linked list

Below is the code to insert node at the end of the single linked list.

#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *head;
void create_linked_list(int element){
struct node *temp=malloc(sizeof(struct node));
temp->data=element;
temp->next=NULL;
if(head==NULL){
head=temp;
}
else{
struct node *ptr=head;
while(ptr->next!=NULL){
ptr=ptr->next;
}
ptr->next=temp;
}
}
void insert_end(int element){
struct node *temp=malloc(sizeof(struct node));
temp->data=element;
temp->next=NULL;
struct node *ptr=head;
while(ptr->next!=NULL){
ptr=ptr->next;
}
ptr->next=temp;
}
int main(){
create_linked_list(30);
create_linked_list(20);
create_linked_list(10);
create_linked_list(18);
insert_end(17);
insert_end(16);
insert_end(23);
//traversing the linked list
struct node *ptr=head;
while(ptr!=NULL){
printf("%d\t",ptr->data);
ptr=ptr->next;
}
}

OUTPUT:

30 20 10 18 17 16 23