I am trying to create a function in c++ to add a new node to the front of the li
ID: 669472 • Letter: I
Question
I am trying to create a function in c++ to add a new node to the front of the list. The function is not working becuause the syntax is wrong. I am unsure why. These are the compiler errors.
LinkedList.cpp:68:27: error: 'm_next' is a private member of 'Node'
newhead->setNext(newhead->m_next) = m_front; //I need to take the M-nex...
^
./Node.h:18:11: note: declared private here
Node* m_next;
^
LinkedList.cpp:68:35: error: expression is not assignable
newhead->setNext(newhead->m_next) = m_front; //I need to take the M-nex...
void LinkedList::addFront(int value)
{
Node* newhead =new Node;
Node* temp =nullptr;
if(isEmpty()) //If the list is empty
{
temp = new Node();
m_front->setValue(value);
m_size++;
}
else if(size()>1)
{
newhead->next(newhead->m_next) = m_front; //I need to take the M-next node in first and set it to the head - m-front.
m_front = newhead;
}
}
//Basic constructor of the linkedlist class
//Constructor
LinkedList::LinkedList()
{
m_size=0;
m_front=nullptr;
}
//Method from the Node.cpp
void Node::setNext(Node* prev)
{
m_next=prev;
}
Node::Node()
{
m_value=0;
m_next=nullptr;
}
Explanation / Answer
In Node class you must have declared m_next as a private variable.
In C++ int is a primitive type, not a class, like in Java. If you return int, you just return it as a constant, so
newhead->setNext(newhead->m_next) = m_front; is not assignable define proper getter methods
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.