c链表实现遇到的错误
想完成一个链表发现有错误,代码如下:
//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; } }
猜测:用的空间没有释放,如果经常这么做可能会导致内存问题