我知道这对C++程序员来说可能是微不足道的,但我是一个努力弄清楚这一点的noobie。在我的主要中,如果我手动打印我的短列表(例如< < < 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);
}
我不认为这是按原样编译的。 'head'是一个指向'ListNode'的双指针,你几乎不能使用'operator->'来访问它的成员。 – 2013-04-24 04:30:22
对不起,我正在编辑我的代码。让我解决它。我最初使用本地副本进行打印,并认为这可能是问题所在,但忘记将其改回。 – user2285010 2013-04-24 04:32:16
@ user2285010最好在'ListNode'中添加一个构造函数,将所有成员变量初始化为0. – 2013-04-24 04:49:16