下面的代码是我整个程序的一个片段。我定义的唯一内容是构造函数(head = 0
),析构函数和一个旨在创建包含20个值的链表的函数。它们应该是随机的(我可以处理),但我需要先修复这个 seg 错误。帮助!
节点的结构类型为:
struct ListNode
{
int value;
ListNode *next;
};
ListNode *head;
法典:
void NumberList::buildSortedList(){
ListNode *newNode;
int number = 1;
int count = 0;
head->value = number;
ListNode *p;
do{
p = head;
while (p->next) { // traverse the list to the end to append new value
p = p->next;
newNode = new ListNode;
newNode->value = number;
newNode->next = NULL;
p->next = newNode;
}
}while (count < 19);
}
while (p->next) { // traverse the list to the end to append new value
p = p->next;
newNode = new ListNode;
newNode->value = number;
newNode->next = NULL;
p->next = newNode;
}
应该是
while (p->next) { // traverse the list to the end to append new value
p = p->next;
}
newNode = new ListNode;
newNode->value = number;
newNode->next = NULL;
p->next = newNode;
如果head
是全局变量,则初始化为 NULL
。取消引用NULL
是非法的。
在取消引用之前,必须将指向有效缓冲区的指针分配给该缓冲区。
void NumberList::buildSortedList(){
ListNode *newNode;
int number = 1;
int count = 0;
if (head == NULL) head = new ListNode; // add this line
head->value = number;
ListNode *p;
do{
p = head;
while (p->next) { // traverse the list to the end to append new value
p = p->next;
} // move this in order not to break the list
newNode = new ListNode;
newNode->value = number;
newNode->next = NULL;
p->next = newNode;
}while (count++ < 19); // add ++ to avoid infinite loop
}