I'm new to programming and C++.
I've managed to succesfully insert multiple nodes from front. Problem is that when printing it starts with the latest node and goes "backwards". I would like it to start with the first node and print forward. Therefore I would like to insert new nodes from the back. But I've tried for many hours and read all kinds of tutorials and feel really stupid because I haven't managed to figure it out.
Please guide me to where the problem is.
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct student {
string firstName;
string lastName;
int no;
int age;
struct student *next;
}*head=NULL;
void add_student(int a);
void print_list();
int main(int argc, char *argv[])
{
int studentNo=0;
char choice;
do {
add_student(studentNo);
cout << endl << "Add another student to the list: (Y/N) ";
cin >> choice;
choice=toupper(choice);
studentNo++;
} while(choice=='Y');
print_list();
system("PAUSE");
return EXIT_SUCCESS;
}
void add_student(int a)
{
struct student *temp=new struct student;
cout <<"\nStudent first name: ";
cin >> temp->firstName;
cout <<"Student last name: ";
cin >> temp->lastName;
cout <<"Student age: ";
cin>>temp->age;
temp->no=a;
if (head==NULL){
temp->next=head;
head=temp;
} else {
struct student *temp1=new struct student;
temp1=head;
while (temp1->next!=NULL) {
temp1=temp1->next;
}
temp->next=NULL;
temp1->next=temp;
head=temp;
}
}
void print_list()
{
struct student *temp=new struct student;
temp=head;
while (temp !=NULL)
{
cout << "\n\nStudent name: " << temp->firstName << " " << temp->lastName;
cout << "\nStudent no: " << temp->no;
cout << "\nStudent age: " << temp->age;
cout << endl << "------------------------------" << endl;
temp=temp->next;
}
cout << endl;
}