gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:18:24 26 4
gpt4 key购买 nike

我知道这对 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com