2013-07-08 37 views
-1

這是我爲鏈接列表編寫的代碼。基本上它只需要輸入並打印它。在編譯時,它不會給出錯誤,但它也不會輸出。我沒有得到這個代碼有什麼問題?幫幫我。打印鏈接列表中沒有輸出

#include<stdio.h> 

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

insert(struct list* node, int data) 
{ 
    node = malloc(sizeof(struct list*)); 
    if (node == NULL) 
    node = data; 
    else 
    node->data = data; 
    node->next = NULL; 
return node; 
} 

printlist(struct list* node) 
{ 
if (node == NULL) 
    printf("Empty list\n"); 
while(node->next != NULL) 
    printf("the list contains %d", node->data); 
    node = node->next; 
} 

main() 
{ 
    struct list* NODE; 
    NODE = malloc(sizeof(struct list*)); 
    insert(NODE, 3); 
    insert(NODE, 5); 
    printlist(NODE); 
} 

回答

2

,那是因爲你不保持你的節點的指針,當你這樣做,也拆除*

node=malloc(sizeof(struct list*)); 

嘗試類似:

struct list * insert(struct list* node ,int data) 
    { 
     struct list * new_elem = malloc(sizeof(*new_elem)); //check !=NULL 
     new_elem->data = data; 
     new_elem->next = NULL; 
     if (node != NULL) 
      node->next = new_elem; 
    return (new_elem); 
} 
+0

+1您指出的第一個錯誤也出現在main()中,第二個'node = data; // insert()'函數中的不兼容類型(也加上這2點),我的回答不完整,因此刪除。 –

1

實際上,它包含了許多錯誤。

改寫插入():

struct list* insert(struct list* node ,int data) //need the type of return value 
{ 
    struct list* newnode; 
    newnode=malloc(sizeof(struct list)); //get rid of '*' 
    //how to insert to a link list? I suggest you make it understand. 
    //in this code, I insert an element in the head. 
    newnode->data = data; 
    //if (node==NULL) 
    // newnode->next = NULL; 
    //else 
    // newnode->next=node; 
    //the code above equals: 
    newnode->next = node; 
    return newnode; 
} 

和的printList(),你不能讓一些代碼空間,而不是塊 「;」 ,這就是說,改變

while(node!=NULL) 
    printf("the list contains %d\n",node->data); 
    node=node->next; 

while(node!=NULL) { 
    printf("the list contains %d\n",node->data); 
    node=node->next; 
} 

犯同樣的錯誤在老插入存在()。

althoght沒有printlist()的返回值的類型,它可以編譯,但我建議添加一個,如void

此外,對於空列表,您需要更改:

if (node==NULL) 
printf("Empty list\n"); 

if (node==NULL) { 
    printf("Empty list\n"); 
    return; 

}

與這個新的插件(),在main()將是:

main() 
{ 
    struct list* NODE = NULL; 
    NODE = insert(NODE,3); 
    NODE = insert(NODE,5); 
    printlist(NODE); 
} 

我測試過後是修復,它的工作。

+1

是的,它的工作:) thnks! – user2456752

+1

@ user2456752好吧,還有一個左側的bug,我在下面編輯,首先是「另外,對於一個空列表,你需要改變......」 – vvy

+0

@ user2456752和'malloc()',你可能需要一個'#include ' – vvy