无法访问链表的相邻节点



我试图在C++中实现一个双链表,但遇到了一个问题。

#include <iostream>
#include <string>
struct Node
{
std::string data;
Node* prev_link;
Node* next_link;
Node(const std::string& data,Node* prev_link=nullptr, Node* next_link=nullptr)
: data{data},prev_link{prev_link},next_link{next_link} {}// constructor
};
Node* insert(Node* new_node,Node* old_node);// insert node before old node
Node* head(Node* node);// returns a pointer to the head i.e. the left end of the linked list
void print_list(Node* node);//takes the head pointer and executes iterative print
void kill_list(Node* tail_node);// deallocates memory by deleting the list
Node* insert(Node* new_node,Node* old_node)
{
if(new_node == nullptr) return old_node;
if(old_node == nullptr) return new_node;
new_node->next_link = old_node;// p of old node connect to new node
if(old_node->prev_link) old_node->prev_link->next_link = new_node;//n of old' node connect to new node if old' node exists
new_node->prev_link = old_node->prev_link;//p of new node connect to old` node
new_node->next_link = old_node;//n of new node connect to old node
return new_node;
}
Node* head(Node* node)
{
while(node->next_link != nullptr) node = node->next_link;
return node;    
}
void print_list(Node* node)
{
while(node)
{
std::cout << node->data;
if(node = node->next_link) std::cout << "<->";// if next node is not an end node 
}
}
void kill_list(Node* tail_node)
{
Node* temp;
while (tail_node)
{
temp = (tail_node->prev_link)?tail_node->prev_link:tail_node->next_link;
delete tail_node;
tail_node = temp;
}
std::cout << 'n' <<"List destroyed" << std::endl;
}
int main()
{
Node* alphabets = new Node("A");
alphabets = insert(new Node("B"),alphabets);
alphabets = insert(new Node("C"),alphabets);
print_list(alphabets);
std::cout << 'n';
std::cout << "Head:" << head(alphabets)->data << std::endl;
std::cout << "Adjacent:" << head(alphabets)->prev_link->data << std::endl;
kill_list(alphabets);
}

输出:

C<->B<->

头部:

fish:"./test1"被信号SIGSEGV(地址边界错误(终止

head((函数返回一个指向head节点的指针(在本例中为a(。链表和头节点都打印正确,但我无法访问与头节点相邻的节点。搞不清我做错了什么。如有任何帮助,我们将不胜感激。


您的错误是因为A的邻居有一个空指针。在您的插入函数中,您有这个if语句

if(old_node->prev_link) old_node->prev_link->next_link = new_node

但是,在A的情况下,没有prev_link,但您仍然希望分配B。因此,将其替换为:

old_node->prev_link = new_node;

修复了该问题。但是,您可能需要再次检查,以便这与您想要的逻辑相对应。

问题是由于没有为head设置prev_link(每个节点的prev链接为零(,insert函数出现错误,您从未设置旧节点的prev_link。

最新更新