Singly Linked list C program :create insertion deletion search display
C Program π
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head,*p=NULL;
void create(int d)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=d;
newnode->next=NULL;
if(head==NULL)
{
head=newnode;
p=newnode;
}
else
{
p->next=newnode;
p=newnode;
}
}
void display()
{
struct node *temp=head;
if (head==NULL)
{
printf("the list is empty");
return;
}
printf("the list elements are : \n");
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
void inp(int pos,int d)
{
struct node *ptr,*p=head;
int i;
ptr=(struct node *)malloc(sizeof(struct node));
ptr->data=d;
if(pos==1)
{
ptr->next=p;
head=ptr;
}
else
{
for(i=1;i<pos-1;i++)
{
p=p->next;
if(p==NULL)
{
printf("overflow\n");
return;
}
}
ptr->next=p->next;
p->next=ptr;
}
}
void dele(int pos)
{
int i=0;
struct node *p,*temp=head;
if(temp==NULL)
{
printf("list is empty.\n");
return;
}
if(pos==1)
{
head=temp->next;
free(temp);
}
else
{
while(i<pos-1)
{
p=temp;
temp=temp->next;
if(temp==NULL)
{
printf("less elements are there.\n");
return;
}
i++;
}
p->next=temp->next;
free(temp);
}
printf("%d node is deleted.",pos);
}
void see(int d)
{
struct node *temp=head;
int i=1,c=0;
if (temp==NULL)
{
printf("list is empty.\n");
return;
}
while(temp!=NULL)
{
if(temp->data==d)
{
printf("%d present at %d node.\n",d,i);
c=1;
}
temp=temp->next;
i++;
}
if(c==0)
{
printf("search unsuccessful.\n");
}
}
int main()
{
int i,n,d,pos,data,op,co=1;
printf("enter no of elements : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter %d node element : ",(i+1));
scanf("%d",&d);
create(d);
}
display();
while(co==1)
{
printf("1.search 2.delete 3.insert 4.traversal\n");
printf("what operation do you want to perform:");
scanf("%d",&op);
switch(op)
{
case 1:
printf("enter the element you want to find: ");
scanf("%d",&data);
see(data);
display();
break;
case 2:
printf("enter the position of element you want to delete : ");
scanf("%d",&pos);
dele(pos);
display();
break;
case 3:
printf("enter the data and position : ");
scanf("%d%d",&data,&pos);
inp(pos,data);
display();
break;
case 4:
display();
break;
default:
printf("enter a valid key...\n");
}
printf("enter 1 to continue or 0 to stop : ");
scanf("%d",&co);
if(co!=1)
{
break;
}
}
return 0;
}
Output :
Comment what you want.
Happy codingπ.
πππ
ReplyDelete