Hi I have a piece of code. It's print for me the numbers I enterd but in reverse order that I would like to. How may I change that?
thx

#include<iostream>
#include<conio.h>
using namespace std;
struct Node
{
 int data;
 Node* link;
};
class Q
{
  public:
         Q();
         void get_input(int);
         void display_input();
  private:
          void display(Node* node); 
          Node* head;
};
int main()
{
  Q q1;
  int number;
  cout<<"How many numbers : ";
  cin>>number;
  for (int i=0;i<number;i++)
  {
  q1.get_input(number);
  }
  q1.display_input();
  
  getch();
  return 0;
}
Q::Q()
{
  head=NULL;
}
void Q::get_input(int number)
{
 cout<<"Enter a number: ";
 
   Node* temp; 
   temp=new Node;
   cin>>temp->data;
   temp->link=head;
   head=temp;
 }
void Q::display_input()
{
  cout<<"The output is equall to: ";
  display(head);
 
}
  
void Q::display(Node* head)
{
  if(head==NULL)
  return;
 cout<<head->data;
  cout<<" ";
 display(head->link);
}

When you add the node to the list in get_input() add it to the tail, not the head. There are at least a couple ways to do that. 1) search for the tail of the list each time you want to add a new node to the tail, or 2) keep another tail pointer, similar to how you do the head pointer.

Hi
I have no clue how to do it. I heard something about tail but don't know how to implement it. Could youi show me a little exercise with it or could you implement with my program.
Thanks

First, when you allocate a new node make sure you set the next pointer to NULL (or 0). Then its just a simple loop to look for the last node (tail) in the list

Node* tail = head;
while( tail->next != NULL)
     tail = tail->next;
// now pointer tail points to the last node in the list
This article has been dead for over six months. Start a new discussion instead.