使用链表(C ++)的段故障队列

时间:2018-10-04 06:06:00

标签: c++ linked-list segmentation-fault queue

以下是新程序员对Queue的尝试。当我尝试在第一个节点中打印数据时,它会在Push()函数中出现错误。看起来front_ptr实际上没有在head_insert中设置。我在这里做错什么,这是完全错误的方法吗?

谢谢。

#include <cstdlib>
#include <iostream>

using namespace std;

class node {
public:
    typedef double data_type;

    node(data_type init_data = 0, node * init_next = NULL) {
        data = init_data;
        next_node = init_next;
    }

    void set_data(data_type new_data) { data = new_data; }

    void set_next(node * new_next) { next_node = new_next; }

    data_type get_data() { return data; }

    node * get_next() { return next_node; }

private:
    data_type data;
    node * next_node; 
};

void head_insert(node::data_type val, node* head_ptr) {
    node* insert_ptr = new node(val, head_ptr);
    head_ptr = insert_ptr;
}

void list_insert(node::data_type val, node* prev_ptr) {
    node* insert_ptr = new node(val, prev_ptr->get_next());
    prev_ptr->set_next(insert_ptr);
}

void head_remove(node* head_ptr) {
    node* remove_ptr = head_ptr;
    head_ptr = head_ptr->get_next();
    delete remove_ptr;
}

void list_remove(node * prev_ptr) {
    node* remove_ptr = prev_ptr->get_next();
    prev_ptr->set_next(remove_ptr->get_next());
    delete remove_ptr;
}

void list_clear(node* head_ptr) {
    while (head_ptr != NULL) {
        head_remove(head_ptr);
    }
}

class queue {
public:
    queue() {
        size = 0;
        front_ptr = NULL;
        rear_ptr = NULL;
    }
    //~queue() {}

    bool empty() { return (size == 0);}

    void push(node::data_type val) {
        if (empty()) {
            head_insert(val, front_ptr);
            cout << "Here: " << front_ptr->get_data() << endl;
            rear_ptr = front_ptr;
        }
        else {
            list_insert(val, rear_ptr);
        }
        size++;
    }

    void pop() {
        if (!empty()) {
            head_remove(front_ptr);
            size--;
        }
    }

private:
    node* front_ptr;
    node* rear_ptr;
    int size;
};

int main() {
    cout << "START" << endl;
    double testVal = 1;
    queue* qList = new queue();
    qList->push(testVal);
    cout << "END" << endl;

    return 0;
}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您的front_ptrpush中仍为空指针,因为head_insert按值接受它。解引用空指针然后会使程序崩溃。使要由函数修改的参数引用诸如void head_insert(node::data_type val, node*& head_ptr)之类的参数。

此外,您可以通过事先进行检查来避免空指针取消引用崩溃,例如:

   cout << "Here: " << (front_ptr ? front_ptr->get_data() : 0./0.) << endl;