LinkedList Insertion at Beginning

Algorithm

INPUT: HEADER IS A POINTER TO THE HEADER NODE OF THE LINKEDLIST AND X IS THE ELEMENT TO BE INSERTED
OUTPUT: LINKEDLIST WITH THE ADDED ELEMENT
DATA STRUCTURE: SINGLY LINKEDLIST

STEP 1: NEW=GETNODE(NODE)
STEP 2: IF(NEW=NULL)THEN
STEP 3: PRINT("MEMORY INSUFFICIENT")
STEP 4: EXIT
STEP 5: ELSE
STEP 6: NEW->DATA=X
STEP 7: NEW->LINK=HEADER->LINK
STEP 8: HEADER->LINK=NEW
STEP 9: ENDIF
STEP 10:STOP

Code

#include <stdio.h>
#include <stdlib.h>
int getnode(int);
void display();
void newnode();
int x;
struct node{
int data;
struct node *link;
};
struct node *prev,*head,*news,*p;
struct node *header;
int main(){
int n;
printf("ENTER THE LIMIT");
scanf("%d",&n);
getnode(n);
return 0;}
void display(struct node *head){
struct node *ptr;
ptr=news;
while(ptr!=NULL){
printf("%d ",ptr->data);
ptr=ptr->link;} }
void newnode(){
 news=NULL;
news=malloc(sizeof(struct node));
 news->data=x;
 news->link=NULL;
 if(news==NULL) {
 printf("memory Insufficient"); }
 else { 
 news->link=header->link;
 header->link=news;} }
int getnode(int n){
header=malloc(sizeof(struct node));
head=NULL;
for(int i=0;i<n;i++){
p=malloc(sizeof(struct node));
scanf("%d",&p->data);
p->link=NULL;
if(head==NULL)
head=p;
else
prev->link=p;
prev=p;
}header->link=head;
display(header);
printf("Enter the number to be inserted at the beginning");
scanf("%d",&x);
newnode();
display(header);
return 0;}

Output

user@computer$ : ENTER THE LIMIT2
1
2
1 2 Enter the number to be inserted at the beginning3
3 1 2

Leave a Comment

Your email address will not be published. Required fields are marked *