无法访问链表的相邻节点

Cannot access adjecent node of linked list

我正在尝试用 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<->A

头:A

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

head() 函数 returns 指向头节点(在本例中为 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(每个节点prevlink为0),insert函数出错,你永远不要设置旧节点的prev_link。