想完成一個鏈表發現有錯誤,代碼如下:
//http://ac.jobdu.com/problem.php?pid=1511
//֮ǰÓÃlistʵÏֵ쬽ñÌìÊÔÒ»ÏÂÓÃstructʵÏÖһϰÉ
//¿´¿´×Ô¼ºÄܲ»ÄÜʵÏÖÒ»¸öÁ´±í
#include<iostream>
using namespace std;
struct Node{
int num;
struct Node *next;
};
int main(void)
{
struct Node n1;
n1.num=1;
struct Node *head;
head=&n1;
n1.next=NULL;
struct Node *tail;
tail=head;
int n;
cin>>n;
while(n)
{
struct Node node;
node.num=n;
node.next=NULL;
(*tail).next=&node;
*tail=node;
cin>>n;
}
struct Node *p;
p=head;
while(p!=NULL)
{
cout<<(*p).num<<endl;
p=p->next;
}
}
最後打印的時候只打印最後一個值,想了想應該是賦值的時候的錯誤,由於賦值是在while循環裡,導致node是局部變量,用完之後就銷毀了,而鏈表也並沒有在初始化的時候給分配相應的空間。所以只存留了最後一個。
解決辦法:事先分配好空間。
看了網上的實現,也都是預先分配好空間的,都使用了malloc,這樣在空間在銷毀之前都是存在的,所以你賦值之後,局部變量沒了,但是值已經賦給相應的空間了。
下邊這樣就是對的了:
#include "stdafx.h"
#include<iostream>
using namespace std;
struct Node {
int num;
struct Node *next;
};
int main(void)
{
struct Node *head;
head = NULL;
struct Node *tail;
tail = head;
int n;
cin >> n;
while (n != -1)
{
struct Node *p=(struct Node *)malloc(sizeof(struct Node));
p->num = n;
p->next = NULL;
if (head == NULL)
{
head = p;
tail = p;
//head=&node;
}
else
{
tail->next = p;
tail = tail->next;
}
// cout<<(*tail).num<<endl;
cin >> n;
}
struct Node *p;
p = head;
// int i = 1;
while (p != NULL)
{
//cout << i++;
cout << (*p).num << " ";
p = p->next;
}
}
猜測:用的空間沒有釋放,如果經常這麼做可能會導致內存問題