【问题标题】:Seg fault Queue using Linked List (C++)使用链表 (C++) 的分段故障队列
【发布时间】:2018-10-04 06:05:59
【问题描述】:

以下是一个新程序员对队列的尝试。当我尝试在第一个节点中打印数据时,它会在 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;
}

非常感谢任何帮助。

【问题讨论】:

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


    【解决方案1】:

    您的front_ptrpush 中仍然是空指针,因为head_insert 按值接受它。取消引用空指针会使程序崩溃。通过void head_insert(node::data_type val, node*&amp; head_ptr)等函数引用参数制作您想要修改的参数。

    此外,您可以通过在之前检查空指针取消引用来避免崩溃,例如:

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

    【讨论】:

    • 感谢您的快速回复。这解决了我的问题。需要重温按值传递与按引用传递。非常感谢@Öö Tiib
    猜你喜欢
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 2014-07-16
    相关资源
    最近更新 更多