如何在我的程序中打破无限循环

时间:2015-03-31 15:50:15

标签: c++ stack queue infinite-loop

我的程序出了问题。我试图把一堆数字放在一个循环链接队列中然后回到堆栈中。该程序编译并运行,但在完成所有程序后,我的程序进入一个空白的无限循环。我假设我是因为函数isQueue.enqueue(temp)部分代码,因为当我删除它时,我的程序不再进入无限循环。问题是我没有看到我做错了什么会让它无限循环。

功能

#include <fstream>
#include <iostream>
#include <cassert>
#include "stack.h"
#include "queuei.h"

void stackToqueue(stack &isStack, queue &isQueue)
{
    int temp;
    stack newStack;
    while (!isStack.isEmpty())
    {
        temp = isStack.pop();
        newStack.push(temp);
    }
    newStack.displayStack();
    isStack = newStack;
    isStack.displayStack();

    while (!newStack.isEmpty())
    {
        temp = newStack.pop();
        isQueue.enqueue(temp);//stuck in loop
    }
    isQueue.displayQueue();
    while (!isQueue.isEmpty())
    {
        temp = isQueue.dequeue();
        newStack.push(temp);
    }
    temp = isQueue.dequeue();
    newStack.push(temp);

    isStack = newStack;

}

queue.cpp

#include "queuei.h"

queue::queue()
{
    rear = NULL;
    front = NULL;
}

bool queue::isEmpty()
{
    if (front == rear)
    {
        return true;

    }
    return false;

}
void queue::enqueue(int element)
{
    nodes *temp = new nodes;
    temp->item = element;
    temp->next = NULL;
    if (front == NULL)
    {
        front = temp;
    }
    else
    {
        rear->next = temp;
    }
    rear = temp;
    rear->next = front;
}
int queue::dequeue()
{
    nodes  *tem = new nodes;
    tem = front;
    if (front == NULL)
    {

        cout << "\nQueue is Emtpty\n";

    }
    else
    {

        front = front->next;

    }
    return tem->item;
}

void queue::dequeue(int remove)
{
    if (front == NULL)
    {

        cout << "\nQueue is Emtpty\n";

    }
    else

    {
        front = front->next;
    }
}


void queue::displayQueue()
{
    nodes *p = new nodes;
    p = front;

    if (front == NULL)
    {
        //queue is empty
    }
    else
    {
        cout << "F ";
        while (p != rear)
        {
            cout << p->item << " ";
            p = p->next;

        }
        cout << p->item;

        cout << " L";

    }

}

1 个答案:

答案 0 :(得分:0)

问题出在 queue :: isEmpty()中,因为当有一个节点并且前面和后面都指向同一节点时它将返回true。检查它们是否为空将解决问题。

bool queue::isEmpty()
{
    if (front == NULL && rear == NULL)
    {
        return true;
    }
    return false;
}