Monday 23 February 2015

Data Structures in C


#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<malloc.h>

struct link
{
int num;
struct link *next;
};

typedef struct link node;
node *startnode;
int n,i;
int flag=0;

void main()
{
int ch;
void create();
void insert();
void del();
void disp();
clrscr();
while(1)
{
printf(“\n 1. Create List”);
printf(“\n 2. Delete Node”);
printf(“\n 3. Insert Node”);
printf(“\n 4. Display”);
printf(“\n 5. Exit”);
printf(“\n Enter your choice:”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
create();
break;
case 2:
del();
break;
case 3:
insert();
break;
case 4:
disp();
break;
case 5:
exit(0);
}
}
}
void create()
{
node *curnode;
startnode=malloc(sizeof(node *));
flag=1;
printf(“Enter the total no in the list:”);
scanf(“%d”,&n);
printf(“Enter the number:”);
scanf(“%d”,&startnode->num);
startnode->next=malloc(sizeof(node *));
curnode=startnode;
for(i=1;i<n;i++)
{
curnode=curnode->next;
printf(“Enter the number:”);
scanf(“%d”,&curnode->num);
curnode->next=malloc(sizeof(node *));
}
}
void disp()
{
int i;
struct link *cnode;
cnode=startnode;
if(flag==0)
printf(“\n List is empty\n”);
else
{
for(i=0;i<n;i++)
{
printf(“%d\n”,cnode->num);
cnode=cnode->next;
}
}
printf(“\n *****************************\n”);
}
void del()
{
int i,p;
node *curnode,*temp;
if(flag==0)
printf(“List is empty”);
else
{
printf(“Enter the position”);
scanf(“%d”,&p);
curnode=startnode;
if(p>n)
printf(“Enter the correct position:”);
else if(p==1)
{
if(p==n)
flag=0;
startnode=curnode->next;
free(curnode);
printf(“\n Node is deleted”);
n=n-1;
}
else
{
for(i=1;i<p-1;i++)
curnode=curnode->next;
temp=curnode->next;
curnode->next=temp->next;
free(temp);
printf(“Node is deleted”);
n=n-1;
}
}
}
void insert()
{
int i,p;
node *newnode,*curnode,*temp;
newnode=malloc(sizeof(node *));
if(flag=0)
printf(“List is empty”);
else
{
printf(“Enter the number:”);
scanf(“%d”,&newnode->num);
printf(“Enter the position:”);
scanf(“%d”,&p);
curnode=startnode;
if(p>n+1)
printf(“Enter the correct position:”);
else if(p==1)
{
newnode->next=startnode;
startnode=newnode;
printf(“\n Node is inserted”);
n=n+1;
}
else
{
for(i=1;i<p-1;i++)
curnode=curnode->next;
temp=curnode->next;
curnode->next=newnode;
newnode->next=temp;
printf(“Node is inserted”);
n=n+1;
}
}
getch();
}

No comments:

Post a Comment