Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Queue Implementation using two stacks-Pointer Doubt and help with code


[size=5]The program task is to implement a queue using two stacks.I understand that pointers need to be passed as parameters like this - pop([b]&[/b]headA). But when I do that, I get an 'incompatible pointer' compile time error. So, when I execute the code like shown below, I get logical error. It doesn't run the way I want it to.
[/size]

[code]#include

typedef struct node{
int data;
struct node *link;
}node;
node *headA = NULL;
node *headB = NULL;


void push(node *,int);
int pop(node *);
void display(node *);
void enQ();
void dQ();

main(){
int choice;
system("cls");
printf("
Welcome to Queue implementation using two stacks.
");
do{
/*system("clear"); */
/* Menu */
printf("
What would you like with your queue?

");
printf("1. Insert an element at the front (EnQ)
2. Delete the last element (DQ)
3. Exit program

Enter your desired choice with the corresponding serial number :

");
scanf("%d",&choice);
system("cls");
switch(choice){

case 1: enQ();
break;
case 2: dQ();
break;
case 3: printf("
Sorry to see you go, hope to see you back soon!
");
getch();
exit(0);
default: printf("
Sorry, That option is unavailable. Try again!

");
getch();
}
}while (choice >= 0);
}


void enQ(){
int add;
int x,y;
printf("
Enter the item
");
scanf("%d",&add);
if(headB == NULL){
push(headA, add);
}
else{
while(headB != NULL){
x = pop(headB);
push(headA, x);
}
push(headA, add);
}
while(headA != NULL){
y = pop(headA);
push(headB, y);
}
display(headB);
}

void dQ(){
int del;
int x,y;
if(headB == NULL){
printf("Queue is empty.");
}
else{
while(headB != NULL){
x = pop(headB);
push(headA, x);
}
del = pop(headA);
printf("
The element deleted is : %d ", del);
while(headA != NULL){
y = pop(headA);
push(headB, y);
}
display(headB);
}
}


void push(node *head, int add){
node *last_node;
last_node = (node*)malloc(sizeof(node));
last_node->data = add;
last_node->link = head;
head = last_node;
}

int pop(node *head){
node *last_node;
int flag = 0;
if(head==NULL)
return flag;
else{
last_node = head;
flag = last_node->data;
head = head->link;
free(last_node);
return flag;
}
}

void display(node *head){
node *my_stack;
if(head == NULL)
printf("
Stack is empty
");
else{
my_stack = head;
printf("
The elements of the queue are :

");
while(my_stack != NULL){
printf("%d ", my_stack->data);
my_stack = my_stack->link;
}
}
getch();
}
[/code]
Sign In or Register to comment.