队列PrintContents函数崩溃程序

时间:2014-09-24 02:33:01

标签: c++ data-structures queue

我为我的数据结构类创建了一个队列数据结构,当我尝试打印空队列的内容时,我的程序不断崩溃。有人可以看看我的功能,并告诉我我搞砸了什么?

 #include <iostream>
using namespace std;

class Node {
public:
    int value;
    Node *next;

    Node(){
        value = -1;
        next = NULL;
    }
};

class Queue {
public:
    Node *top;

    Queue() {
        top = NULL;
    }

    void enqueue(int x){ //enqueue() adds items to the queue. Adds them to the head (top) of the list.
        //two cases: 1) queue could be empty. If so, this new node is at the top of the stack.
        //2) queue has nodes in there, all we need to do is make this the top node
        Node *temp = new Node;
        temp->value = x;
        if(top == NULL){
            //stack is empty
            top = temp;
        }
        else{
            temp->next = top;
            top = temp;
        }
    }

    void dequeue() {
        //Function to delete the bottom most item in queue.
        Node *chase, *follow;
        chase = follow = top;
        if(top == NULL){
            //The queue is empty, you can't remove anything or anyone from it.
            cout << "The queue is empty." << endl;
            return;
        }
        else{
            while(chase->next != NULL) { 
                follow = chase;
                chase = chase->next;
            }
            delete chase;
            follow->next = NULL;
        }
    }

    void printContents(){
        Node *temp;
        temp = top;

        if(temp == NULL){
            cout << "The queue is empty." << endl;
        }
        else{
        while(temp){ //Same as saying while( temp!= NULL)
            cout << temp->value << "--->";
            temp = temp->next;
            }
        cout << "NULL" << endl;
        }

    }
};

int main(){
Queue queueObj;
int choice, value;

while(1){
    cout << "Press 1 to add items to the top of the queue." << endl;
    cout << "Press 2 to delete items from the bottom of the queue." << endl;
    cout << "Press 3 to view the contents of the queue." << endl;
    cout << "Enter anything else to exit the program." << endl;
    cin >> choice;

    switch(choice){
    case 1: cout << "Enter value that you want to add: " << endl;
            cin >> value;
            queueObj.enqueue(value);
            break;
    case 2: queueObj.dequeue();
            break;
    case 3: queueObj.printContents();
            break;
    default: exit(1);
    }
}
system("pause");
return 0;
}

0 个答案:

没有答案