你能发现这个链表代码中的4个错误吗?

Dav*_*zar 2 linked-list nodes

我刚刚接受了测试,我只能发现2,我们的教授在返回时没有给我们正确答案..想知道你们是否可以帮助我发现这个代码中的4个错误链表...

int main() {
  struct node 
 {
     int data;
     node * next; 
 }

// create empty list
node * list;

// insert six nodes at front of list
node *n;
for (int i=0;i<=5;i++)
{
  n = new node;
  n->data = i;
  n->next = list;
}
// print list
n = list;
while (!n) 
{
  cout << n->data << "  ";
  n = n->next; 
}
cout << endl;
Run Code Online (Sandbox Code Playgroud)

Som*_*ame 5

  • struct node;在它的声明结束时遗漏了
  • list 没有初始化为 NULL
  • list 节点插入后没有指向头部
  • 未检查节点分配是否成功
  • 打印循环不正确 - 应该while(n)代替while(!n)