繁体   English   中英

如何实现一个包含整数和空指针的双向链表?

[英]How to implement a doubly linked list that accommodates integers and void pointers?

我正在尝试实现我自己的通用数据结构版本来改进我的编码。 我有一个任务需要一个双向链表,它可以保存int和 void 指针, void * data 我的结构有两种成员类型,一种用于int ,一种用于void*

struct Node {
    int data;
    void* pntData;
    Node* next;
    Node* previous;
};
class LL {
private:
    Node* head;
    Node* tail;
    int size;
public:
    LL();
    void insert_front(int data);
    void insert_front(void* data);//overloaded for void pointer data types
    void printLL();//removed unrelated methods
};

这是我的 Node 结构和双向链表类。 我已经能够编写处理int所有方法。 我的困惑在于将空指针作为参数并将其添加到具有int值的同一个链表中。

我知道 void 指针是一个可以指向任何类型数据的指针,但我很困惑我应该如何将 void 指针作为参数并将其添加到我用这个构造函数初始化的同一个链表中:

LL::LL() {
    head = nullptr;
    tail = nullptr;
    size = 0;
}

这是我的附加函数,在那里我想到了重载,以便如果参数是指针,则数据将作为void* pntData添加到我的类变量中。 如果参数是 int,则数据将作为int添加到我的类变量中。

void LL::insert_front(int data) {
    Node* temp = new Node();
    if (head == nullptr) {
        head = temp;
        temp->previous = nullptr;
        temp->next = nullptr;
        temp->data = data;
        tail = temp;
    }
    else {
        temp->previous = nullptr;
        temp->next = head;
        temp->data = data;
        head->previous = temp;
        head = temp;
    }
    size++;
}

void LL::insert_front(void* data) {
    Node* temp = new Node();
    if (head == nullptr) {
        head = temp;
        temp->previous = nullptr;
        temp->next = nullptr;
        temp->pntData = data;
        tail = temp;
    }
    else {
        temp->previous = nullptr;
        temp->next = head;
        temp->pntData = data;
        head->previous = temp;
        head = temp;
    }
    size++;
}

问题可能出在我的printLL()函数中,该函数可能需要一个 if/else 来确定是否需要打印int或需要打印void* pntData

请指出我正确的方向。

根据您的评论,您希望printLL()打印void*指针指向的对象。

那是不可能的。 void*指针没有关于它指向的类型的信息,因此您不能取消引用该指针。

如果你想这样做,那么你需要在Node存储一个额外的指向处理函数的指针, printLL()将调用每个Node来打印它的void* 然后你需要在指针类型上制作insert_*函数模板,这样你就可以找出正确的函数指针来存储提供的类型,即:

struct Node {
    int data;
    void* pntData;
    Node* next;
    Node* previous;
    void(*print)(void*) = nullptr; // Initialize with null pointer to indicate that no `void*` is stored.
};

//...

template<typename T>
void LL::insert_front(T* data) {
    Node* temp = new Node();
    //...
    temp->print = [](void* ptr){
        if(ptr != nullptr)
            std::cout << *static_cast<T*>(ptr);
        else
            // What to do if we stored a null pointer for `void*`
    };
    //...
}

//...

void LL::printLL() {
    //...
    if(node->print != nullptr)
        node->print(node->pntData);
    //...
}

我有一种感觉,这不是练习想让你做的,但正如我在评论中所说的,这对我来说首先没有意义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM