Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

#include<stdio.

h>
#include<conio.h>
#include<alloc.h>
void display(struct node **HEAD);
void append(struct node **HEAD, int num);
void insert_begin(struct node **HEAD, int num) ;
void insert_after(struct node **HEAD, int x, int num);
int sum(struct node **HEAD);
struct node
{
int data;
struct node *next;
};
void main()
{
struct node *HEAD;
HEAD=NULL; clrscr();
//printf("Enter the data to add it to the linked list:\t");
//scanf("%d", &num);
append(&HEAD,10);
append(&HEAD,15);
append(&HEAD,20);
append(&HEAD,25);
insert_begin(&HEAD, 18);
insert_after(&HEAD, 15, 67);
display(&HEAD);
printf("\nThe Sum of all nodes is:\t%d",sum(&HEAD));
getch();
}
void insert_after(struct node **HEAD, int x, int num)
{
struct node *NEW, *PTR;
NEW=malloc(sizeof(struct node));
NEW->data=num; NEW->next=NULL;
PTR=*HEAD;
if(*HEAD==NULL)
{
printf("Empty Linked list");
getch();
exit(0);
}
while(PTR->next!=NULL)
{
if(PTR->data==x)
{
NEW->next=PTR->next;
PTR->next=NEW; break;
}
PTR=PTR->next;
}

}
void insert_begin(struct node **HEAD, int num)
{
struct node *NEW;
NEW=malloc(sizeof(struct node));
NEW->data=num; NEW->next=*HEAD;
*HEAD=NEW;

}
void append(struct node **HEAD, int num)
{
struct node *PTR, *NEW;

NEW=malloc(sizeof (struct node));


NEW->data=num; NEW->next=NULL;
PTR=*HEAD;
if(*HEAD==NULL)
{
*HEAD=NEW;
}
else
{
while(PTR->next!=NULL)
PTR=PTR->next;
PTR->next=NEW;
}
}
void display(struct node **HEAD)
{
struct node *PTR;
PTR=*HEAD;
printf("The linked list is:\n");
while(PTR!=NULL)
{
printf("%d->",PTR->data);
PTR=PTR->next;
}
printf("NULL");
}
int sum(struct node **HEAD)
{
struct node *PTR; int s=0;
PTR=*HEAD;
while(PTR!=NULL)
{
s=s+PTR->data;
PTR=PTR->next;
}

return(s);
}

You might also like