hi im currently learning about linked list. Ive created a code which is supposed to let you type some numbers, then display them. i did this mostly by using information on the internet(code examples) and such. Hence there are obvious mistakes a bits i do not understand. Here is my code:

#include <iostream>
using namespace std;

struct nodeType {
    int info;
    nodeType *link;
};
nodeType *head = NULL;

nodeType* buildListForward()
{
  nodeType *first,*newNode, *last;
  int num;
  cout<<"enter numbers";
  cin >>num;
  first=NULL;
  while(num!=-1)
  {
    newNode = new nodeType;     
    newNode->info =num;
    newNode->link = NULL;
    if(first==NULL)            
    {
    first = newNode;
    last= newNode;
    }
    else
    {
      last->link = newNode;
      last = newNode;
    }
    cin>>num;
   }
   return first;
}

void display() {
    struct nodeType *list = head;
    while(list) {
        cout << list->info <<" ";
        list = list->link;
    }
    cout << endl;
}

int main() {
    buildListForward();
    display();
    system("pause");
    return 0;
}

My question is, when i run the code i can type in the numbers until i type -1. it is then supposed to display what i typed. but it does not?

any help is greatly appreciated.

Recommended Answers

All 3 Replies

you are not saving the pointer to head node returned fro, list building routine. You are also not using global head pointer in the display, but ininitialized local one? Pass head node as parameter.

changed it to this:
still does not work :(

#include <iostream>
using namespace std;

struct nodeType {
    int info;
    nodeType *link;
};
nodeType *head = NULL;

nodeType* buildListForward()
{
  nodeType *first,*newNode, *last;
  int num;
  cout<<"enter numbers";
  cin >>num;
  first=NULL;
  while(num!=-1)
  {
    newNode = new nodeType;     
    newNode->info =num;
    newNode->link = NULL;
    if(first==NULL)            
    {
    first = newNode;
    last= first;
    }
    else
    {
      last->link = newNode;
      last = newNode;
    }
    cin>>num;
   }
   return first;
}

void display(nodeType *&first) {


nodeType *temp;
temp=first;
cout<<"RESULTS"<<endl;
while(temp!=NULL)
{
cout<<temp->info<<"  "<<endl;
}



}

int main() {
    nodeType *first;    
    buildListForward();
    display(first);
    system("pause");
    return 0;
}

i ended up scrapping the entire code and starting from scratch. following some other tutorials found on net :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.