繁体   English   中英

在 c++ 中实现通用双链表

[英]Implementing a Generic Double linked list in c++

我已经实现了一个相当简单的双链表概念。 我不知道我做错了什么。 我尝试将节点的成员变量设为公开,但没有帮助。 朋友 class 也没有帮助? 这里的非类类型是什么?

d_list.h

#include "node.h"
#ifndef NODE_H
#define NODE_H

template<class T>
class d_list{
    private:
       int list_size;
       T* head;
       T* tail;  

    public:
       //parametrized Default constructor
       d_list(T* h=nullptr, T* t=nullptr):head(h),tail(t){}

       //get Head of the List
       T* gethead(){return this->head;}
       T* gettail(){return this->tail;}
       void addnodeastail(T* new_node){
           if(this->head==nullptr){
              this->head=new_node;//this->head will point towards new_node  
              this->tail=this->head;
              this->list_size=list_size+1;
           }
           else{

                this->tail= new_node;
                this->tail->next=new_node->previous;
           }
       }
};
#endif

'''

节点.h

template<class T>
    class Node{
        private:
            Node* next;
            Node* previous;
            T data;

        public:
            Node()=default;
            Node(T dta):data(dta){}
            ~Node(){}
    };

主文件

#include<iostream>
#include"d_list.h"
using namespace std;

int main(){

    d_list<int> d1;
    cout<<d1.gethead()<<endl;
    cout<<d1.gettail()<<endl;
    int var=20;
    int* n1= &var;
    int var2 =40;
    int* n2= &var2;
    d1.addnodeastail(n1);
    d1.addnodeastail(n2);
    cout<<d1.gethead()<<endl;
    cout<<d1.gettail()<<endl;
    return 0;
}

我收到的错误类似于

In file included from main.cpp:2:
d_list.h: In instantiation of 'void d_list<T>::addnodeastail(T*) [with T = int]':
main.cpp:14:24:   required from here
d_list.h:28:29: error: request for member 'next' in '*((d_list<int>*)this)->d_list<int>::tail', which is of non-class type 'int'
   28 |                 this->tail->next=new_node->previous;
      |                 ~~~~~~~~~~~~^~~~
d_list.h:28:44: error: request for member 'previous' in '* new_node', which is of non-class type 'int'
   28 |                 this->tail->next=new_node->previous;
      |                                  ~~~~~~~~~~^~~~~~~~

template<class T>
class d_list{
    private:
       int list_size;
       T* head;
       T* tail; 

您声明headtail是指向模板类型T的指针。

这意味着对于d_list<int>你实际上有

int* head;
int* tail;

这没有任何意义,你的头和尾指针应该是指向列表中第一个和最后一个节点的指针:

Node<T>* head;
Node<T>* tail;

并且在向列表中添加元素时,您需要创建新的Node<T>实例来保存数据,并将节点添加到列表中。

问题是headtail不应该是T ,而是node<T>

Node<T>* head;
Node<T>* tail;

请记住, T是您要在列表中保留的 object 的类型。 它没有与之关联的链接。 因此,如果您按当前编写的方式执行d_list<int> ,则模板化代码将如下所示:

int* head;
int* tail;

它们没有相互链接,这只是一个指向int的指针(如果您使用了类似new的东西,则为int的列表)。 要创建链接,您需要使用Node ,因此无论它们存储在 memory 的哪个位置,它们都将具有逻辑连接。 那样的话, d_list<int>会变成这样:

Node<int>* head;
Node<int>* tail;

这将允许您使用节点来开发int的逻辑连接列表,这正是您想要的链表。

暂无
暂无

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

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