Singly linked list in c language
in C and CPP, Tips and Tricks
#include<stdio.h>
#include<process.h>
struct node
{
int data;
struct node *next;
};
typedef struct node *singly;
singly createlist()
{
int x;
singly head,tail,tmp;
head=NULL;
printf("\n enter value(-99 to stop)");
scanf("%d",&x);
while(x!=-99)
{
tmp=(singly)malloc(sizeof(struct node));
tmp->data=x;
if(head==NULL)
{
head=tail=tmp;
}
else
{
tail->next=tmp;
tail=tmp;
}
tail->next=NULL;
printf("\n Enter value(-99 to stop)");
scanf("%d", &x);
}
return(head);
}
void traverse(singly head)
{
singly p=head;
while(p!=NULL)
{
printf("%d --> ",p->data);
p=p->next;
}
}
singly inserthead(singly head,int ins)
{
singly tmp;
tmp=(singly)malloc(sizeof(struct node));
tmp->data=ins;
if(head==NULL)
{
printf("\n error insert");
}
else
{
tmp->next=head;
head=tmp;
}
return(head);
}
singly insertbefore(singly head, int srch,int ins)
{
singly p=head,tmp;
while(p!=NULL)
{ if(p->next->data==srch)
{
break;
}
p=p->next;
}
if(p!=NULL)
{
tmp=(singly)malloc(sizeof(struct node));
tmp->data=ins;
tmp->next=p->next;
p->next=tmp;
}
else
{
printf("\n error insert");
}
return(head);
}
singly deletetail(singly head)
{
singly p=head,q=head->next;
while(q->next!=NULL)
{
p=p->next;
q=q->next;
}
p->next=NULL;
free(q);
return(head);
}
singly deleteafter(singly head,int srch)
{
singly p=head,q=head->next;
while(p->next!=NULL)
{
if(p->data==srch)
{
break;
}
p=p->next;q=q->next;
}
if(p->next==NULL)
{
printf("\n delete error");
}
else
{
p->next=q->next;
free(q);
}
return(head);
}
int main()
{
singly head;int ch,ins;char cnt;int srch;
do{
printf("\n1. create list\n2. traverse\n3. insert as head\n4. insert before\n5. Delete tail\n6. Delete after\nEnter your choice : ");
scanf("%d",&ch);
switch(ch){
case 1:
head=createlist();
break;
case 2:
traverse(head);
break;
case 3:
printf("\nenter value to insert : ");
scanf("%d",&ins);
head=inserthead(head,ins) ;
break;
case 4:
printf("\n enter value to insert :");
scanf("%d",&ins);
printf("\n enter value to search :");
scanf("%d",&srch);
head=insertbefore(head,srch,ins) ;
break;
case 5:
head=deletetail(head);
break;
case 6:
printf("\n enter value to search");
scanf("%d",&srch);
head=deleteafter(head,srch) ;
break;
}
fflush(stdin);
printf("\ndo you want to continue (y/n) : ");
scanf("%c",&cnt);
}while(cnt=='y');
}
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7462577112023113"
data-ad-slot="1814817697"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
Related