Sorted Linked List implementation in C

include “stdio.h”
include “stdlib.h”
include “conio.h”

void del(int data);
void insert(int value);
void display();

struct node
{
int data;
struct node *link;
};

struct node *top=NULL,*temp, *temp1, *temp2, *temp3;

int main()
{
int choice,data;

while(1) //infinite loop is used to insert/delete infinite number of elements in linked list
{

printf(“n1.Insertn2.Deleten3.Displayn4.Exitn”);
printf(“nEnter ur choice:”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:

printf(“Enter a new element :”);
scanf(“%d”,&data);
insert(data);
break;

case 2:

printf(“Enter the value to be deleted from sorted linked list :”);
scanf(“%d”,&data);

del(data);
break;

case 3:
display();
break;
case 4:
exit(0);
}

}
getch();
return 0;
}

void insert(int data)
{

temp=(struct node *)malloc(sizeof(struct node));
temp->data=data;

if(top == NULL)
{

temp->link=NULL;
top=temp;

}
else            // top not null
{
temp1 = top ;
while(temp1 != NULL)
{
if(temp1->data >= data)   // list element is smaller …

{
if(temp1 == top)   // list element is head …
{
temp->link = temp1;

top = temp;
break;

}
else // list element is not head ..
{

temp->link = temp1;
temp2->link = temp;
break;
}

}
else
{

if(temp1->link == NULL)
{
temp->link = NULL;
temp1->link = temp;
break;

}
else
{
temp2 = temp1;
temp1 = temp1->link;
}

}

}

}
// creating a space for the new element.

}

void del(int data)
{
struct node *temp,*var;
temp=top;
int i=0;
while(temp!=NULL)
{
if(temp->data == data)
{      i = 1;   // Flag ..
if(temp==top)
{
top=temp->link;
free(temp);
break;
}
else
{
var->link=temp->link;
free(temp);
break;

}
}
else
{
var=temp;
temp=temp->link;
}
}
if(i == 1)
{
printf(“data deleted from list is %d”,data);

}
else
{
printf(“n The required data, %d is not found in the list. go look somewhere else”,data);

}
}

void display()
{
temp=top;
if(temp==NULL)
{
printf(“nStack is emptyn”);
}

while(temp!=NULL)
{
printf(” %d ->”,temp->data);
temp=temp->link;
}

}

Leave a Reply