I have been given the framework to implement a doubly linked list. I am 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* dfor. 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.pListis the head of the list. Inside thePushFrontmethod,pListis referred to asthis.Elementlooks 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 aprevandnext, so perhaps aninsert_beforeand aninsert_after. The linked list, that has a front.Element*pis 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 :)