跟蹤C中鏈接列表中的頭節點

[英]Keeping track of the head node in Linked List in C


    typedef struct node
{
    int data;
    struct node* next;
}node;

node * display(node * head)
{
    node * tmp = head;
    printf("%d\n", tmp->data);
    tmp = tmp->next;
    printf("%d\n", tmp->data);
}

node * create()
{
    // create nodes
    node * head = NULL;
    head = malloc(sizeof(struct node));

    // assign tmp to the head of the node
    node *tmp = NULL;
    tmp = head;

    // place data into head node
    head->data = 2;
    printf("%d\n", head->data);

    // move to next null and create space, then insert data
    head = head->next;
    head = malloc(sizeof(node));
    head->data = 5;
    printf("%d\n", head->data);

    display(tmp);
}




int main(int argc, char *argv[]) 
{   
    create();

    return 0;
}

With this code, I'm trying to create a simple linked list, and pass the head pointer to a function called 'display'. However, when I run the program, the numbers printed are "2" and "159088" instead of just "2" and "5". How should I be passing and keeping track of the head pointer?

使用這段代碼,我試圖創建一個簡單的鏈表,並將頭指針傳遞給一個名為'display'的函數。但是,當我運行程序時,打印的數字是“2”和“159088”而不是“2”和“5”。我應該如何通過並跟蹤頭部指針?

1 个解决方案

#1


0  

You're failing to actually link your list. You never point head->next to the node you alloc for the second value. Try a change like this:

您未能真正鏈接您的列表。您永遠不會將head->指向您為第二個值分配的節點旁邊。嘗試這樣的更改:

// create next node, then insert data
head->next = malloc(sizeof(node));
head = head->next; 
head->data = 5; 
printf("%d\n", head->data);

You set head to head->next. That does nothing , becuase you set it to something else the next line. Mallocing a ne

你設定了頭 - >下一個。這沒有任何作用,因為你把它設置為下一行的其他東西。 Mallocing an ne


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2018/08/12/720c4009a79e3cb2bcb9ac909411b22.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com