Here is a linked list:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Arrival
{
string arrAddress;
double distance;
string roadCategory;
struct Arrival* next;
};
class ArrivalList
{
private:
struct Arrival* head;
public:
bool addArrival(string oneAddress, double distance, string roadCategory);
};
bool ArrivalList::addArrival(string oneAddress, double distance, string roadCategory)
{
Arrival* temp;
Arrival* current=new Arrival();
current=head;
temp=new Arrival();
temp->arrAddress=oneAddress;
temp->distance=distance;
temp->roadCategory=roadCategory;
int f=0;
while(1)
{
if(current==NULL)
{
temp->next=NULL;
head=temp;
f=1;
break;
}
else if(oneAddress>=current->arrAddress && oneAddress<current->next->arrAddress)
{
temp->next=current->next;
current->next=temp;
f=1;
break;
}
else
{
current=current->next;
}
}
cout<<head->arrAddress;
if(f)
{
return true;
}
else
{
return false;
}
}
int main()
{
ArrivalList li;
li.addArrival("jjjjj",0.8999,"I");
li.addArrival("aaaaa",0.888,"k");
}
I want the value of head persist within the multiple call to the function addArrival.But it is changing.I want to to start the loop from 'current' value which should be the value of head after the first call but it is changing and starting from NULL everytime,I suppose.
I want that everytime I call the function it should get the value of updated head and start looping,but the value is not saving for head after the first call.
Your
ArrivalListclass is not initializing itsheadmember, nor is it freeing the list when finished using it, thus leaking the nodes.And, your
addArrival()method has several other problems as well, including:Try something more like this instead:
Online Demo
On the first call, the list is empty, so
jjjjjgets added as the newhead.On the second call,
aaaaais "less than"jjjjj, so it gets added as the newheadandjjjjjbecomes the 2nd node in the list.On the third call,
lllllis "more than"jjjjj, so it gets added as the last node in the list.On the fourth call,
kkkkkis "more than"jjjjjand "less than"lllll, so it added between those nodes in the list.