Does anyone know how does a Self-Referential Class Linked List code looks like?
I tried reading Deital but the codes were confusing and there was no example of the main function. Furthermore, I can't seem to find help on Google.
class Node
{
public:
Node( int ); // constructor
void setData( int ); // set data member
int getData() const; // get data member
void setNextPtr( Node * ); // set pointer to next Node
Node *getNextPtr() const; // get pointer to next Node
private:
int data; // data stored in this Node
Node *nextPtr; // pointer to another object of same type
}; // end class Node
I'm not sure how to continue the main function. Can anyone please give me some links to Self-Referential Classes Linked List codes or provide them here?
This codes appends "node" to the end of the list provided that the value "next" was set to 0 before. Otherwise, the behavior is undefined (don't use NULL, use 0 instead). You should perhaps initialize "next" to 0 in the node constructor.
Sorry. This time the code is working right. I copied and paste from Visual Studio 2008 but the indentations disappear. How do I search for data that I've inserted?
Loop over each element, like you did in setNextPtr, and compare the value of the node with the value you are looking for. (Searching in linked lists requires time Ω(n))
bool deleteANode(Node* List, Node* nToDelete){
Node* prev=NULL;
Node* cur=NULL;
for(cur=List; cur != NULL; prev=cur,cur=cur->getNextPtr() ){
if(cur->getData() == nToDelete->getData()){// Found it
//check
if(prev==NULL){// this is the first node
List= cur->getNextPtr() ;
}else{
prev->setNextPtr(cur->next);
}
// delete the cur
delete cur;
returntrue;
}
}
returnfalse;// not in the list
}