2017-04-13 103 views
-1

我無法將元素添加到單個鏈接列表的末尾。我試圖尋找其他問題,但我無法找到解決方案。我無法將元素添加到C中的鏈接列表末尾

的代碼是:

#include<stdio.h> 
#include<stdlib.h> 

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

void PushE(struct node** head,int data); 

int main(){ 

    struct node* a = NULL; 
    PushE(&a,3); 
    PushE(&a,4); 
} 

void PushE(struct node** headRef, int data){ 


    struct node* current = *headRef; 
    struct node* nNode; 
    nNode = (struct node*)malloc(sizeof(struct node)); 
    nNode->data = data; 
    nNode->next= NULL; 

    if(current == NULL) 
    current = nNode; 
    else{ 
    while(current->next != NULL) 
     current = current->next; 

    current->next = nNode; 
    } 

} 

誰能幫我實現這一點。

+0

[請參閱爲什麼不投)在'C'的malloc'的返回值('和家人討論。(HTTP: //stackoverflow.com/q/605845/2173917)。 –

+1

「struct node」的定義在哪裏? –

+0

我不知道如何複製粘貼更改簽名.....東西從聲明的中間.... –

回答

4

問題是在這裏:

if(current == NULL) 
    current = nNode; // <-- 

你怎麼現在?

struct node* current = *headRef; 

現在這裏是一個指針headRef指出的複製!您需要直接指定給*headRef

+0

謝謝阿空加瓜, –

1

在這個if語句

if(current == NULL) 
    current = nNode; 

有改變局部變量的電流。頭指向的指針沒有改變。所以退出該功能後,原始列表將保持不變。

該功能可以聲明和定義下列方式

int PushE(struct node ** head, int data); 

// ... 

int PushE(struct node ** head, int data) 
{ 
    struct node *nNode = malloc(sizeof(struct node)); 
    int success = nNode != NULL; 

    if (success) 
    { 
     nNode->data = data; 
     nNode->next = NULL; 

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

     *head = nNode; 
    } 

    return success; 
} 
相關問題