Stephen Rivera
Stephen Rivera

Reputation: 3

C++ linked list adding a new node to the beginning of the list

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

Answers (5)

Austin Garrett
Austin Garrett

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

AntonioM
AntonioM

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

user2891462
user2891462

Reputation: 3333

Think carefully about what you have and what you need to do:

  • You have two nodes that you care about: the current head and your new nodePtr.
  • You want 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:

  1. Create your new node nodePtr.
  2. Make nodePtr->next point to head.
  3. Make head point to nodePtr

Upvotes: 0

eshirima
eshirima

Reputation: 3867

To create a new node to the head of a list, follow these steps

  1. Create a temporary node holding your value
  2. Set the temporary node's next to point to the head
  3. Set the head to temporary

Upvotes: 2

SgtDroelf
SgtDroelf

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

Related Questions