用c ++创建链接列表

时间:2013-12-28 17:40:35

标签: c++ list linked-list

我试图在c ++中创建一个从末尾插入元素的链表。我有以下代码

#include<iostream>

using namespace std;

//Define a structure
    struct Node{
        int info;
        Node* next;
    } *start, *newptr, *current, *ptr;

Node* createNewNode(int);
void insertEnd(Node*);
void display(Node*);

int main(){
    char ch='y';
    while(ch=='y')
    {
        int inf;
        //Initialize the start pointer to NULL
        start = NULL;

        //Prompt the user for information
        cout<<"Enter the information -> ";
        cin>>inf;

        //Call the function to create a new node
        newptr = createNewNode(inf);
        cout<<"New node created successfully \n";

        //Insert the node in the beginning
        insertEnd(newptr);

        //Traversal
        display(start);

        //Asks the user for input
        cout<<"Want to enter more -> ";
        cin>>ch;
    }


    return 0;

}

Node* createNewNode(int a)
{
    ptr = new Node;
    ptr->info = a;
    ptr->next = NULL;
    return ptr;
}

void insertEnd(Node* p)
{
    if(start == NULL){
        start = p;
        current = p;
    }else {
        current->next = p;
        current = p;
    }
}

void display(Node* p)
{
    while(p!=NULL){
        cout<<p->info<<"->";
        p=p->next;
    }
}

当我编译程序运行正常但它不显示完整列表。它仅显示用户最近在列表中插入的数字。这段代码有什么问题?

1 个答案:

答案 0 :(得分:2)

每次迭代都会重置列表的开头。

int main(){
    char ch='y';
    while(ch=='y')
    {
        int inf;
        //Initialize the start pointer to NULL
        start = NULL; // remove this line and do it before the while loop