C Linked List Implementation errors

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.