I have been given the framework to implement a doubly linked list. I am getting stumped on the PushFront() method. The method should add the provided element to the front of the linked list and it should return the address to the new head node. I am confused about how to access the current head of the list so I can assign it to the pNext pointer. The PushFront() method looks like this so far:
Element* Element::PushFront(Element* d){
Element* newElement = new Element(Data()); // Allocate space for new element
newElement->ElementData = d->ElementData; // Assign ElementData to the new element
newElement->pNext = // Head address
newElement->pPrev = NULL;
return nullptr;
}
Element Class Constructor:
Element::Element(Data d){
ElementData = d;
pNext = NULL;
pPrev = NULL;
}
Data Class:
Data::Data(){
Name = "Unknown";
SN = 0;
Program = "Unknown";
}
Data::Data(string NameStr, unsigned int sNumber, string Prog) :
Name(NameStr), SN(sNumber), Program(Prog) {};
Main:
Element* pList = new Element(Data("Cam", 12345, "Testing1"));
Element newE(Data("Bob", 335567, "Testing2"));
pList = pList->PushFront(&newE);
My understanding is that you would typically provide the address of the head when calling PushFront(), however since I am not provided that I am unsure of how I can access it.
Element* d
for. Just to get the data out of it? There has to be a better use for it or you'd just pass in the data. – user4581301pList
is the head of the list. Inside thePushFront
method,pList
is referred to asthis
. – user3386109Element
looks like it should be a link. It should not know what a head is because the only things a link should know is what other links it's been attached to and the data it contains. A Link might be a head, but it shouldn't know that. The head is a detail only the linked list should know. Similar withPushFront
. A Link shouldn't have a front. It's just got aprev
andnext
, so perhaps aninsert_before
and aninsert_after
. The linked list, that has a front. – user4581301Element*p
is passed intoPushFront()
, then you could as well write in main:... Element (Data("Cam", 12345, "Testing1"));
And then pass the address of the automatic variable. Which in turn would render destruction, removal etc. nigh impossible to implement :) – BitTickler