我已经使用两个队列编写了堆栈代码,但是当我尝试从堆栈中压入和弹出值时,代码没有给出输出。 这是完整的代码
#include <iostream>
#include <stdlib.h>
using namespace std;
struct Queue{
int front;
int rear;
int capacity;
int *arr;
};
int isFull(Queue *q){
return ((q->rear+1)%q->capacity == q->front);
}
int isEmpty(Queue *q){
return (q->front==-1);
}
void push(Queue *q,int data){
if(!isFull(q)){
//chk if the first element is going to be inserted
if(isEmpty(q)){
q->front=0;
}
q->rear=(q->rear+1)%q->capacity;
q->arr[q->rear]=data;
}
}
int removeFront(Queue *q){
if(!isEmpty(q)){
int result=q->arr[q->front];
if(q->front==q->rear){
q->front=q->rear=-1;
}
else{
//increase the front of the queue
q->front=(q->front+1)%q->capacity;
}
return result;
}
return -1;
}
int pop(Queue *q1,Queue *q2){
//move all the items fro the queue 1 to queue 2
while (!isEmpty(q1))
{
push(q2,removeFront(q1));
}
//store and return the element from the queue 2
int res=removeFront(q2);
while (!isEmpty(q2)) {
push(q1, removeFront(q2));
}
return res; //return the popped itm
}
int main(){
//initialization
Queue *q1=new Queue;
Queue *q2=new Queue;
q1->front=q2->rear=-1;
q1->capacity=q2->capacity=10;
q1->arr=(int *)malloc(q1->capacity*sizeof(int));
q2->arr=(int *)malloc(q2->capacity*sizeof(int));
当我将项目推入堆栈并尝试打印弹出的结果时。它不显示任何输出。
push(q1,10);
push(q1,20);
push(q1,30);
cout<<pop(q1,q2);
//free the allocated memory
delete[] q1->arr;
delete[] q2->arr;
delete q1;
delete q2;
return 0;
}
检查了代码但无法理解。
问题是您没有正确初始化队列:
q1->front=q2->rear=-1;
这使得
q1-rear
和 q2->front
未初始化,因此您会得到未定义的行为。由于 q2->front
可能不等于 -1,因此 while
中的最后一个 pop
循环将永远不会完成:removeFront
调用永远不会达到 front
等于 rear
的点,因为 front
%
运算符为非负数,并且 rear
为 -1。
解决方案是将所有四个成员正确初始化为-1:
q1->front=q1->rear=-1;
q2->front=q2->rear=-1;
不是你的问题,但这不是你用 C++ 编程的方式。
malloc
。不要将 arr
定义为指针,而是定义为向量。Queue
定义为带有方法的类。Stack