简体   繁体   中英

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;
}

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM