Hey all. I've been playing around with link lists to learn it on my own so I decided to write a small program with it that just takes in data for two nodes and display them.
Code:
#include<iostream>
using namespace std;
struct batsman{
string name;
int fours;
int sixes;
int innings;
batsman*ptr;
batsman();
int aggregate();
};
batsman::batsman(){
name = "\0";
fours = 0;
sixes = 0;
innings = 0;
}
int batsman::aggregate(){
return (4*fours)+(6*sixes);
}
void display(batsman*);
batsman*insert(batsman*,string,int,int);
int main(){
batsman *topptr = NULL,*temp=NULL;
int x,f,s;
string name;
for(x=1;x<=2;x++){
cout<<"Name:";
cin>>name;
cin.get();
cout<<"Fours:";
cin>>f;
cout<<"Sixes:";
cin>>s;
cin.get();
temp = insert(topptr,name,f,s);
cout<<endl<<endl;
}
display(temp);
cin.get();
return 0;
}
batsman* insert(batsman*topptr,string name,int fours, int sixes){
batsman*node;
node = (batsman*)malloc(sizeof(batsman));
if(node!=NULL){
node->name = name;
node->fours = fours;
node->sixes = sixes;
node->innings = node->aggregate();
node->ptr = topptr;
topptr = node;
return topptr;
}else{
cout<<"Memory Not Available";
}
}
void display(batsman*topptr){
while(topptr!=NULL){
cout<<"Name:\t\t"<<topptr->name<<endl;
cout<<"Fours:\t\t"<<topptr->fours<<endl;
cout<<"Sixes:\t\t"<<topptr->sixes<<endl;
cout<<"Aggregate Score:"<<topptr->innings<<endl;
topptr = topptr->ptr;
}
}
However as it is...only the lastly entered node displays which makes sense because as it is the link list operates as a stack...but why doesn't it go on to print the first node even though within the while loop of the display function i've incremented topptr by doing topptr=topptr->ptr?