簡體   English   中英

指針C鏈表添加總是NULL

[英]Pointers C Linkedlist Adding Always NULL

我已經編寫了一個函數,用於在C中添加到單鏈表的末尾。但是,我沒有得到的是為什么head元素為NULL,為什么在連續添加后它仍保持為NULL。

該結構定義如下:

typedef struct node* node;

struct node {
    int data;
    node next;
}

總的來說,我有這個:

node test = NULL;
add(test,1);
add(test,2);
add(test,3);

函數add的定義如下:

void add(node head, int newData) {
    node n = createNode(newData);
    if (head==NULL) {
        head = n;
        return;
    }
    else {
        node tmp = head;
        while (tmp->next != NULL) {
           tmp = tmp->next;
        }
        tmp = n;
    }
}

createNode的定義如下:

node createNode(int data) {
    node n = (node) malloc(sizeof(struct node));
    n->next = NULL;
    n->data = data;
    return n;
}

我感到困惑的是,如果我首先初始化head(節點test = createNode(1)),然后繼續添加其余值,那么add函數就可以正常工作。 但是,如果我將測試節點留為NULL,它不會添加任何值嗎? 這是怎么回事

寫功能add如下方式

void add( node *head, int newData ) 
{
    node n = createNode( newData );

    while ( *head ) head = &( *head )->next;

    *head = n;
}

或者你可以用下面的方式寫

void add( node *head, int newData ) 
{
    while ( *head ) head = &( *head )->next;

    *head = createNode( newData );
}

並稱它為

node test = NULL;

add( &test, 1 );
add( &test, 2 );
add( &test, 3 );

考慮到必須在函數add之前聲明函數createNode並且您錯過了結構定義中的分號

struct node {
    int data;
    node next;
}
^^^

同樣,將相同的標識符用於結構標簽和指向相同結構的指針也不是一個好主意。

typedef struct node* node;

至少寫這樣的東西會更好

typedef struct node* node_ptr;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM