user58569
user58569

Reputation: 47

linkedlist, cannot link the node to head

I just lost the direction in the middle of somewhere, I cannot figure out what is wrong with my code. A functions below is my append function to put node into list.

void AppendNode(struct s_list *list, unsigned int data)
{
    if (list == nullptr)
        return;

    struct s_node *tempHead = list->head;
    struct s_node *newNode = new s_node;
    newNode->next = nullptr;

    while (tempHead != nullptr)
        tempHead = tempHead->next;

    tempHead = newNode;
}

I'm calling this function 100 times and it won't link the new node with current list at all. It shouldn't be hard to find the problem but I'm so bad. Give me some advice. Thanks.

//*************************************************************************//

Thanks for all reply but I still have a same problem. I already allocate the head node for my list then pass it to the function. Now, I changed to pass head of list directly, not list anymore but still have a same issue...

void AppendNode(struct s_node *head, unsigned int data)
{
    if (head == nullptr)
        return;

    struct s_node *tempHead = head;
    struct s_node *newNode = new s_node;
    newNode->next = nullptr;

    while (tempHead != nullptr)
        tempHead = tempHead->next;

    tempHead = newNode;
}

Upvotes: 0

Views: 63

Answers (2)

ayaohsu
ayaohsu

Reputation: 3

Or if you are trying to append the node to the end of list, just do:

while (tempHead->next != nullptr)
    tempHead = tempHead->next;

tempHead->next = newNode;

Upvotes: 0

Beta
Beta

Reputation: 99094

Your tempHead runs right off the end of the list; nothing in this function changes the list.

First deal with the case of an empty list:

if(list->head == NULL)
{
  list->head = newNode;
  return;
}

Then advance with caution:

while (tempHead->next != nullptr)
  tempHead = tempHead->next;

tempHead->next = newNode;

Upvotes: 1

Related Questions