struct Node
{
int num;
struct Node *next;
struct Node *prev;
};
struct Node *start=NULL;
struct Node *end=NULL;
void addAtEnd(int num)
{
struct Node *t;
t=(struct Node *)malloc(sizeof(struct Node));
t->num=num;
t->next=NULL;
t->prev=NULL ;
if(start==NULL)
{
start=t;
end=t;
}
else
{
end->next=t;
t->prev=end;
end=t;
}
}
void insertAtTop(int num)
{
struct Node *t;
t=(struct Node*)malloc(sizeof(struct Node));
t->num=num;
t->next=NULL;
t->prev=NULL;
if(start==NULL)
{
start=t;
end=t;
}
else
{
t->next=start;
start->next=t;
start=t;
}
}
void insertAtPosition(int num,int pos)
{
struct Node *p1;
int x;
struct Node *t;
t=(struct Node *)malloc(sizeof(struct Node));
t->num=num;
t->next=NULL;
t->prev=NULL;
x=1;
p1=start;
while(x
{
p1=p1->next;
x++;
}
if(p1==NULL)
{
if(p1==start)
{
start=t;
end=t;
}
else
{
end->next=t;
t->prev=end;
end=t;
}
}
else
{
if(p1==start)
{
t->next=start;
start->prev=t;
start=t;
}
else
{
t->next=p1;
t->prev=p1->next;
p1->prev->next=t;
p1->prev=t;
}
}
}
void removeFromPosition(int pos)
{
struct Node *p1;
int x;
if(start==NULL)
{
printf("Invalid Position\n");
return;
}
x=1;
p1=start;
while(x
{
p1=p1->next;
x++;
}
if(p1==NULL)
{
printf("Invalid Position\n");
return;
}
if(p1==start && p1==end)
{
start=NULL;
end=NULL;
}
else
{
if(p1==start)
{
start=start->next;
start->prev=NULL;
}
else
{
if(p1==end)
{
end=end->prev;
end->next=NULL;
}
else
{
p1->prev->next=p1->next;
p1->next->prev=p1->prev;
}
}
}
free(p1);
}
void traverseTopToBottom()
{
struct Node *t;
t=start;
while(t!=NULL)
{
printf("%d\n",t->num);
t=t->next;
}
}
void traverseBottomToTop()
{
struct Node *t;
t=end;
while(t!=NULL)
{
printf("%d\n",t->num);
t=t->prev;
}
}
void main()
{
int ch, num, pos;
while(1)
{
printf("1. Add a node at end\n");
printf("2. Insert a node at top\n");
printf("3. Insert a node at a position\n");
printf("4. Remove a node from a position \n");
printf("5. Traverse -Top To Bottom\n");
printf("6. Traverse - Bottom To Top\n");
printf("7. Exit\n");
printf("Enter your choice:");
scanf("%d",&ch);
if(ch==1)
{
printf("Enter a number to add at end:");
scanf("%d",&num);
addAtEnd(num);
}
if(ch==2)
{
printf("Enter a number to insert at top");
scanf("%d",&num);
insertAtTop(num);
}
if(ch==3)
{
printf("Enter a number to insert:");
scanf("%d",&num);
printf("Enter the position where you want to insert:");
scanf("%d",&pos);
insertAtPosition(num,pos);
}
if(ch==4)
{
printf("Enter positionj of the node to remove:");
scanf("%d",&pos);
removeFromPosition(pos);
}
if(ch==5)
{
traverseTopToBottom();
}
if(ch==6)
{
traverseBottomToTop();
}
if(ch==7)
{
break;
}
}
}
No comments:
Post a Comment