Program for singly linked list

#include stdio.h
#include conio.h
#include malloc.h

struct node
{
int data;
struct node *next;
}*start=NULL;

void create(int);
void addatbeg(int);
void addinbet(int,int);
void del(int);
void search(int);
void display();

void main()
{
int x,pos,n,i,ch;
clrscr();
printf("\nSINGLE LINKED LIST\n");
do
{
printf("\n\n1. CREATE LIST \
\n2. ADD ELEMENT AT BEGINNING \
\n3. ADD ELEMENT IN BETWEEN \
\n4. DELETE AN ELEMENT \
\n5. SEARCH AN ELEMENT \
\n6. DISPLAY \
\n7. EXIT \
\nEnter Your Choice...");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
printf("\nEnter No. of Elements in List: ");
scanf("%d",&n);
for(i=1;i<=n;i++) { printf("\nEnter Element %d: ",i); scanf("%d",&x); create(x); } break; } case 2: { printf("\nEnter The Element: "); scanf("%d",&x); addatbeg(x); break; } case 3: { printf("\nEnter The Element: "); scanf("%d",&x); printf("\nEnter The Position of Element: "); scanf("%d",&pos); addinbet(x,pos); break; } case 4: { printf("Enter Element to be Deleted: "); scanf("%d",&x); del(x); break; } case 5: { printf("Enter Element to be Searched: "); scanf("%d",&x); search(x); break; } case 6: { display(); break; } case 7: { exit(0); break; } } } while(ch!=7); getch(); } void create(int a) { struct node *tmp,*q; tmp=malloc(sizeof(struct node *)); tmp->data=a;
tmp->next=NULL;
if(start==NULL)
{
start=tmp;
}
else
{
q=start;
while(q->next != NULL)
{
q=q->next;
}
q->next=tmp;
}
}

void addatbeg(int a)
{
struct node *tmp;
tmp=malloc(sizeof(struct node *));
tmp->data=a;
tmp->next=start;
start=tmp;
}

void addinbet(int a,int p)
{
struct node *q,*tmp;
int i;
q=start;
if(p==1)
{
addatbeg(a);
return;
}
for(i=1;inext == NULL)
{
printf("\nPOSITION NOT VALID!!\n");
return;
}
q=q->next;
}
tmp=malloc(sizeof(struct node *));
tmp->data=a;
tmp->next=q->next;
q->next=tmp;
}

void del(int a)
{
struct node *q,*tmp;
tmp=malloc(sizeof(struct node *));
if(start->data==a)
{
tmp=start;
start=start->next;
free(tmp);
return;
}
q=start;
while(q->next != NULL)
{
if(q->next->data == a)
{
tmp=q->next;
q->next=tmp->next;
free(tmp);
return;
}
q=q->next;
}
printf("\nELEMENT NOT FOUND!\n");
}

void search(int a)
{
struct node *q;
if(start->data==a)
{
printf("\nELEMENT FOUND\n");
return;
}
q=start;
while(q->next != NULL)
{
if(q->next->data == a)
{
printf("\nELEMENT FOUND\n");
return;
}
q=q->next;
}
printf("\nELEMENT NOT FOUND!\n");
}

void display()
{
struct node *q;
if(start==NULL)
{
printf("\nLIST EMPTY!!\n");
}
else
{
q=start;
while(q != NULL)
{
printf("%d -> ",q->data);
q=q->next;
}
printf("NULL");
}
}

No comments:

Post a Comment