c簡單的鏈表錯誤及改正

    如下代碼運行時崩潰:node

#include <iostream>
using namespace std;
struct node
{
int num;
struct node * next;
}; node * creat()
{
node * head=NULL;node*HEAD=head;
cout<<"輸入數字,組成鏈表,0退出"<<endl;
int a;
while(cin>>a&&a!=0)
{
node * add=new node;
add->num=a;
head->next=add;
head=head->next;
}
head->next=NULL;
return HEAD;
}
int main()
{
node* head=creat();
while(head->next!=NULL)
{
cout<<head->next->num;
head=head->next;
}
ios

緣由:post

最初你的head=null,並無指向一個節點,head->next沒有意義。
 
解決:head = new head; 動態分配一個頭結點
相關文章
相關標籤/搜索