programminginc.net

C Language Programming

  • Home
  • C Examples
Home > Data Structure C Programming Examples > C program to insert a node in singly linked list

C program to insert a node in singly linked list

C program using pointers to insert a node in singly linked list at middle, beginning and end is as follows.

// C Program Singly Linked List to create and to insert a node in the middle, beginning, and end#//

#include <stdio.h>
#include <conio.h>
#include <alloc.h>
struct linkedlist
{int info;
struct linkedlist *next;
};
typedef struct linkedlist node;
node* makenode(int);
node* insertbeg(node*);
void insertmid(node*);
void insertend(node*);
main()
{node *head, *p, *z;
int x; char c='y';
clrscr();
printf("Enter the number");
scanf("%d", &x);
head=makenode(x);
p=head;
printf("Do you want to continue");
fflush(stdin);
scanf("%c", &c);
while (c!='n')
{printf("Enter the number");
scanf("%d", &x);
z=makenode(x);
p->next=z;
p=z;
printf("Do you want to continue");
fflush(stdin);
scanf("%c", &c);
}
//head=insertbeg(head);//
insertmid(head);
//insertend(head);//
p=head;
while(p!=NULL)
{printf("\t%d", p->info);
p=p->next;
}
getch();
return 0;
}
node* makenode(int x)
{
node *z;
z=(node*)malloc(sizeof(node));
z->info=x;
z->next=NULL;
return z;
}
node* insertbeg(node *head)
{node *p;
int x;
printf("\nEnter number to insert");
scanf("%d", &x);
p=makenode(x);
p->next=head;
return(p);
}
void insertmid(node *head)
{
node *p, *q;
int x,y;
printf("Enter the previous number");
scanf("%d", &x);
for(p=head; p->info!=x; p=p->next);
printf("Enter the new info to insert middle");
scanf("%d", &y);
q=makenode(y);
q->next=p->next;
p->next = q;
}
void insertend(node *head)
{node *p, *q;
int x;
for (p=head; p->next!=NULL; p=p->next);
printf("\nEnter the new value to insert at end");
scanf("%d", &x);
q=makenode(x);
p->next=q;
}
//end of program//
  • Singly Linked List Data Structure Program C
  • C program to insert a node in singly linked list
  • Doubly linked list in data structure using C Program
  • Insertion in doubly linked list data structure Using C Program
  • Deletion in doubly linked list data structure Using C Program

Copyright © 2021  programminginc.net