C Linked List Implementation errors
If you want to complete a linked list and find an error, the Code is as follows:
//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;}}
At last, only the last value is printed. I thought it should be an error when assigning values. Because the assignment is in the while LOOP, node is a local variable, it is destroyed after use, and the linked list does not allocate the corresponding space during initialization. So only the last one remains.
Solution: Allocate space in advance.
After reading the implementation on the Internet, all the space is pre-allocated and all use malloc, so that the space exists before it is destroyed. Therefore, after you assign a value, the local variable is gone, however, the value has been assigned to the corresponding space.
Below is the right one:
#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;}}
Guess: the space used is not released. If you do this frequently, it may cause memory problems.