0

I'm trying to create a linked list in c++ that inserts elements from the end. I have the following code

#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;
    }
}

When I compile the program runs fine but it does not display the complete list. It only displays the number recently inserted in the list by the user. What's wrong with this code?

3
  • You have the list backwards... Commented Dec 28, 2013 at 17:44
  • have you tried debugging? Commented Dec 28, 2013 at 17:47
  • why the global variables. remove them. Commented Dec 28, 2013 at 17:51

1 Answer 1

2

Your start of the list is reset in every iteration.

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, mate! I would like to ask one more thing. When I run the program the cmd prompt window is triggered instantly but the program initializes after few seconds say, 10-15 sec. I have tried compiling with CodeBlocks, DevC++ and MSVC++.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.