0

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.

2
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by BryantFury
0

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.

Edited by pyTony

0

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

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.