我正在尝试从头开始在 C++ 中自己实现一个单链表,到目前为止,我的第一个方法 append():
#include <iostream>
using namespace std;
struct ListNode{
int key_value;
ListNode *next;
};
class List{
public:
List();
void append(int key);
private:
ListNode *head;
ListNode *tail;
};
List::List(){
head = NULL;
tail = head;
}
void List::append(int key){
ListNode *newnode;
newnode->key_value = key;
newnode->next = NULL;
if(head == NULL){
head = newnode;
tail = head;
}
else{
tail->next = newnode;
tail = newnode;
}
return;
}
int main(){
try{
List l1;
l1.append(1);
//l1.append(2);
//l1.append(3);
//l1.append(5);
}
catch (exception const& ex) {
cerr << "Exception: " << ex.what() <<endl;
return -1;
}
}
它编译时没有任何警告或错误,但在执行期间我只收到 message Bus error: 10
。似乎我初始化和使用ListNode变量和指针的方式有问题,任何见解都将不胜感激。