Code for Simple LINKED LIST in C-Programming
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;
void insertb(int x)
{
struct node *temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("memory unavailable");
}
temp->data=x;
temp->next=NULL;
if(head!=NULL)
{
temp->next=head;
}
head=temp;
}
void inserte(int x)
{
struct node *t1=head;
struct node *temp=(struct node *)malloc(sizeof(struct node));
temp->data=x;
temp->next=NULL;
if(temp==NULL)
{
printf("memory unavailable");
}
if(head==NULL){
head=temp;
}
while(t1->next!=NULL)
{
t1=t1->next;
}
t1->next=temp;
}
void insertn(int x,int index)
{
struct node *temp1=(struct node *)malloc(sizeof(struct node));
struct node *temp2;
int i=0;
temp1->data=x;
temp1->next=NULL;
if(index==1)
{
temp1->next=head;
head=temp1;
}
temp2=head;
for(i=0;i<(index-2);i++)
{
temp2=temp2->next;
}
temp1->next=temp2->next;
temp2->next=temp1;
}
void deleteb()
{
struct node *temp1=head;
if(head==NULL)
{
printf("list is empty");
}
head=head->next;
free(temp1);
}
void deletee()
{
struct node *temp1=head;
struct node *temp2;
if(head==NULL){
printf("list is empty");
}
while(temp1->next!=NULL)
{
temp2=temp1;
temp1=temp1->next;
}
if(temp1==head){
head=NULL;
}
else{
temp2->next=NULL;
}
free(temp1);
}
void deleten(int index)
{
struct node *temp1=head;
struct node *temp2;
int i=0;
if(index==1)
{
head=temp1->next;
free(temp1);
}
for(i=0;i<(index-2);i++)
{
temp1=temp1->next;
}
temp2=temp1->next;
temp1->next=temp2->next;
free(temp2);
}
void display()
{
struct node *temp=head;
printf("printing list :");
while(temp!=NULL)
{
printf("|%d|%u|->",temp->data,temp->next);
temp=temp->next;
}
printf("\n");
}
void main()
{
int n,max=30,x,p;
clrscr();
printf("1 for insert beginning\n2 for insert end\n3 for insert at position\n4 delete beginning\n5 for delete end\n6 for delete at position\n7 for display\n 8 for exit");
ll1:
printf("enter choice:");
scanf("%d",&n);
switch(n)
{
case 1:printf("enter number : ");
scanf("%d",&x);
insertb(x);
display();
goto ll1;
case 2:printf("enter number :");
scanf("%d",&x);
inserte(x);
display();
goto ll1;
case 3:printf("enter position : ");
scanf("%d",&p);
printf("enter number :");
scanf("%d",&x);
insertn(x,p);
display();
goto ll1;
case 4:deleteb();
display();
goto ll1;
case 5:deletee();
display();
goto ll1;
case 6:printf("enter position : ");
scanf("%d",&p);
deleten(p);
display();
goto ll1;
case 7:display();
goto ll1;
case 8:goto exit;
}
exit:
getch();
}
Comments
Post a Comment