c++ - 当我试图通过我的函数打印我的列表时出现段错误

标签 c++ linked-list

我知道这对 C++ 程序员来说可能是微不足道的,但我是一个试图弄清楚这个问题的菜鸟。总的来说,如果我手动打印我的短列表(cout << head->value 等),它会工作,但是当我使用我的打印功能时,我会遇到段错误。我一直在尝试使用调试器,但我不太擅长 unix/c++,我在尝试解决这个问题时感到很沮丧。

#include <iostream>
using namespace std;

class ListNode
{
    public:
    int value;
    ListNode* next;
};

void insertAtHead(ListNode** head, int value)
{
    ListNode *newNode = new ListNode;
    newNode->value = value;
    if(head == NULL)
    {
        *head = newNode;
        newNode->next = NULL;
    }
    else
    {
        newNode->next = *head;
        *head = newNode;
    }
}

void printList(ListNode* head)
{
    while(head != NULL)
    {
        cout << head->value << "->";
        head = head->next;
    }
}
//inserts after the node with given value
void insertAfterNode(ListNode** head,ListNode** newNode, int value)
{
    ListNode* current = *head;
    while(current != NULL && (current->value != value)) 
    {
            //cout << "Im Here";
            current = current->next;
            cout << current->value;
    }
    (*newNode)->next = current->next;
    current->next = *newNode;
}

int main()
{
    ListNode *head;
    insertAtHead(&head, 5);
    insertAtHead(&head, 10);
    ListNode* newNode = new ListNode;
    newNode->value = 8;
    newNode->next = NULL;
    insertAfterNode(&head,&newNode, 5);
printList(head);
}

最佳答案

在你的函数中检查这个修改

void insertAtHead(ListNode** head, int value)
{
    ListNode *newNode = new ListNode;
    newNode->value = value;

    newNode->next = *head;
    *head = newNode;
}

void printList(const ListNode* head)
{
    while(head != NULL)
    {
        cout << head->value << "->";
        head = head->next;
    }
}

insertAtHead 中,你正在传递一个双指针,所以比较应该是这样的。

添加了在访问之前检查 *head 是否为空。如果 null 添加新节点作为 head

void insertAfterNode(ListNode** head,ListNode** newNode, int value)
{
    ListNode* current = *head;
    if (current  != NULL)
    {
       while(current != NULL && (current->value != value)) 
       {
            //cout << "Im Here";
            current = current->next;
            cout << current->value;
       }
       (*newNode)->next = current->next;
       current->next = *newNode;
    }
    else
    {
      *head = *newNode;
    }
}

并且在使用前在main中初始化head

int main()
{
    ListNode *head = NULL;
    insertAtHead(&head, 5);
    printList(head); // <== note: by-value, not by address or reference.

关于c++ - 当我试图通过我的函数打印我的列表时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16183375/

相关文章:

java - LinkedList vs ArrayList - 询问实现思路的观点

javascript - 编写一个函数来检测链表中的循环(Floyd's alg)...逻辑看起来正确,但找不到错误

arrays - 将链表转换为数组(伪代码)

c++ - 删除单链表中间的元素?

c++ - 我应该在我的 C++ std 随机分布上调用 reset() 来清除隐藏状态吗?

c++ - 在链表上实现随机访问迭代器

c++ - 函数终止后的C++字符串文字变化

c++ - 编写一个函数来删除单向链表中的节点(尾部除外),只允许访问该节点

c++ - 构建 libiconv 库

c++ - 插入两个相互引用的 SQL 表而无需执行单独的查询?