I am in my way of studying the linked list chapter of C++..
So i go through this code below intended of understand it.

#include <iostream>
using namespace std;

struct nodeType
{
       int info;
       nodeType *link;
};

void printList (nodeType *first)
{
     nodeType *current;
              current=first;
              while (current != NULL)
              {
                    cout<<current->info<<" ";
                    current=current->link;
              }
              cout<<"\n";
}

nodeType* buildBackward ()
{        nodeType *first, *newNode, *last;
          int num;

          cout<<"Enter a list of intergers ending with -999."<<endl;
          cin>>num;
          first=NULL;

          while (num!=-999)
          {    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;
}

int main()
{
    nodeType *first=buildBackward();
    printList(first);
    system("pause");
    return 0;
}

But i do not understand the uses of pointer in this fraction of code(i mean the one on the right,nodeType*) :

nodeType* buildBackward ()
{        
............................
}

As far as i know the pointer on the right indicates that the value is fetched from the location.But what it really does on the funtion above?
I just hope that somebody could explain it to me.

Thank You :)

Recommended Answers

All 3 Replies

The function's name buildBackward doesn't describe what's been done in the function. Basically, the function builds a list with all the numbers entered by user. After the number -999 is encountered, it returns a pointer to the first node of the list. Having this pointer, the printList function iterates until the end is reached (printing the value each node stores as it iterates).

Hope I explains well.

Hi,
What nodeType *first=buildBackward(); does is to :
1. Declare a variable 'first' of type, pointer to nodeType.

2. call buildBackward() to build the linked list

3. And finally a pointer to the first node in the linked list is returned and assigned to the pointer variable 'first'.

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.