C++ 从双链接列表类打印单个节点
我目前正在尝试实现三个方法:get_first()、get_last()和print_node()。get_first()将返回列表的头部,get_last()将返回尾部,print_node()将只打印发送给它的节点的数据字段。我正在尝试实现,但是我所做的任何更改都会不断出现指针错误 这是我的node.h头:C++ 从双链接列表类打印单个节点,c++,doubly-linked-list,C++,Doubly Linked List,我目前正在尝试实现三个方法:get_first()、get_last()和print_node()。get_first()将返回列表的头部,get_last()将返回尾部,print_node()将只打印发送给它的节点的数据字段。我正在尝试实现,但是我所做的任何更改都会不断出现指针错误 这是我的node.h头: class Node { private: int data; Node *next; Node *prev; f
class Node
{
private:
int data;
Node *next;
Node *prev;
friend class LinkedList;
};
class LinkedList
{
private:
Node *head;
Node *tail;
public:
LinkedList();
~LinkedList();
bool empty();
void insert_left(int v);
void insert_right(int v);
Node* get_first();
Node* get_last();
void print_list();
void print_node(Node *n);
void remove_left();
void remove_right();
protected:
void add(Node *v, int d);
void remove(Node *v);
};
以下是my list.cpp类实现文件的相关部分:
#include <iostream>
#include "node.h"
using namespace std;
LinkedList :: LinkedList()
{
head = new Node;
tail = new Node;
head->next = tail;
tail->prev = head;
}
LinkedList :: ~LinkedList()
{
while(!empty())
{
remove_left();
}
delete head;
delete tail;
}
void LinkedList :: add(Node *v, int d)
{
Node *u = new Node;
u->data = d;
u->next = v;
u->prev = v->prev;
v->prev->next = v->prev = u;
}
void LinkedList :: print_list()
{
Node *tmp = head;
while(tmp != NULL)
{
cout << tmp->data << endl;
tmp = tmp->next;
}
}
void LinkedList :: print_node(Node *n)
{
Node *tmp = n;
cout << tmp->data << endl;
}
Node LinkedList :: get_first()
{
return head;
}
Node LinkedList :: get_last()
{
return tail;
}
我不确定要做的具体更改,但我认为这与如何在get_first()和last()函数中返回头部有关。请原谅文章的长度。您在函数声明中返回Node*,但在定义中,您将Node作为返回类型。用这个
Node* LinkedList :: get_first()
{
return head;
}
Node* LinkedList :: get_last()
{
return tail;
}
数据成员
head
和tail
定义为
Node *head;
Node *tail;
bool empty() const { return ( head == nullptr ); }
也就是说,它们是指向节点的指针。因此,如果任何函数返回head
或tail
,则其返回类型必须是Node*
所以这些成员函数定义
Node LinkedList :: get_first()
{
return head;
}
Node LinkedList :: get_last()
{
return tail;
}
你错了。它们返回head和tail,但没有返回类型节点*
,并且它们的定义与类中的定理声明不一致
构造函数定义也是错误的。看起来像
LinkedList :: LinkedList() : head( nullptr ), tail( nullptr )
{
}
在这种情况下,成员函数empty应声明为
bool empty() const;
定义为
Node *head;
Node *tail;
bool empty() const { return ( head == nullptr ); }
函数成员的签名与它们的定义不匹配