我嘗試打印一個鏈表,但它沒有打印列表中的所有成員。可以解釋我的代碼中存在什麼問題?是代碼行(newhead = newhead-> next)移動列表的其餘部分是否在另一個函數?鏈接列表打印問題?
#include <stdio.h>
#include <stdlib.h>
struct test_struct{
int data;
struct test_struct *next;
};
struct test_struct* create();
void add_node();
int main()
{
add_node();
return 0;
}
void add_node()
{
struct test_struct* head = create();
struct test_struct* newhead;
newhead = malloc(sizeof(struct test_struct));
newhead->data=2;
newhead->next=head;
head=newhead;
while(newhead->next != NULL)
{
printf("%d\n",newhead->data);
newhead=newhead->next;
}
}
struct test_struct* create()
{
struct test_struct* head=NULL;
struct test_struct* temp = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL==temp)
{
printf("error in memory");
return 0;
}
temp->data=5;
temp->next=head;
head=temp;
return head;
}
你期望輸出什麼?你得到了什麼輸出? – Chowlett
給一些輸出! –
我想把它當作2 5. – Rishav