Reputation: 3
I'm struggling with how to link the new node I am creating to the rest of my linked list.
template <class T>
void LinkedList<T>::addBeg(T value)
{
ListNode *nodePtr = head;
head = nodePtr->next;
head = nodePtr;
nodePtr = new ListNode(value);
}
I know what I did wrong here: the new value is not associated the linked list at all.
I think I know what I need to do. I'm pretty sure what I need to do is create the new value, insert into the beginning of the existing list, and then redefine head to be the newly created value.
The problem I'm having, is I don't know how to do this.
So, what I think I need to do (at least logically), is set
*nodePtr = new Listnode(value);
Then set
nodePtr = head;
then set
head = nodePtr-> next;
and then set the
new ListNode(value) = head;
Am I on the right track? I can't shake the nagging feeling that I'm not correctly linking the new ListNode to the existing list and I can't figure out if I am making the wrong steps or if I'm missing a step.
Upvotes: 0
Views: 2999
Reputation: 510
If you say nodePtr = head;
then you're just overwriting the pointer you just made. You want to change nodePtr->next = head; head = nodePtr;
Upvotes: 0
Reputation: 655
You are on the wrong way. The solution is create the new node, link the next node to head, and after refer the head to new node:
template <class T>
void LinkedList<T>::addBeg(T value)
{
ListNode *nodePtr = new ListNode(value);
nodePtr->next = head;
head = nodePtr;
}
Upvotes: 0
Reputation: 3333
Think carefully about what you have and what you need to do:
head
and your new nodePtr
.nodePtr->next
to point to your current head, and update head to point to nodePtr
so that this is the first node in the list.The order in which you do things is important: if you assign the new value of head
before making nodePtr->next
point to the previous value, you will lose your whole list!
Therefore:
nodePtr
.nodePtr->next
point to head.nodePtr
Upvotes: 0
Reputation: 3867
To create a new node to the head of a list, follow these steps
Upvotes: 2
Reputation: 349
You first have to create a new Node, then link it to the current head. Then you switch the reference from your previous head to the newly created node.
ListNode *newHead = new ListNode;
newHead->next = head;
head = newHead;
Upvotes: 1