程序任务是使用两个栈来实现一个队列。我理解需要像这样传递指针作为参数 - pop(**&**headA)
。但是当我这样做时,我得到一个“不兼容的指针”编译时错误。因此,当我执行如下所示的代码时,出现逻辑错误。它没有按照我想要的方式运行。
#include<stdio.h>
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("\n\tWelcome to Queue implementation using two stacks.\n");
do{
/* Menu */
printf("\n\tWhat would you like with your queue?\n\n");
printf("1. Insert an element at the front (EnQ)\n2. Delete the last element (DQ)\n3. Exit program\n\nEnter your desired choice with the corresponding serial number :\n\n");
scanf("%d",&choice);
system("cls");
switch(choice){
case 1: enQ();
break;
case 2: dQ();
break;
case 3: printf("\n\tSorry to see you go, hope to see you back soon!\n");
exit(0);
default: printf("\n\tSorry, That option is unavailable. Try again!\n\n");
}
}while (choice >= 0);
}
void enQ(){
int add;
int x,y;
printf("\n\tEnter the item\n");
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("\n\tThe 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("\n\tStack is empty\n");
else{
my_stack = head;
printf("\n\tThe elements of the queue are : \n\n\t");
while(my_stack != NULL){
printf("%d\t", my_stack->data);
my_stack = my_stack->link;
}
}
}