我想构建仅具有add_to_end和show_list函数的链接列表,但当我想要显示head
时,尽管item
工作(查看代码),但列表崩溃。无法在C中创建正确的链接列表
#include <stdio.h>
#include <stdlib.h>
typedef struct Data
{
int x;
int y;
struct Data * next;
}List;
void AddEnd(List * item, List * head);
void Show(List * head);
int main(void)
{
int choice;
List item;
List * head;
List * temp;
head = NULL;
while(printf("q - quit - Enter 1 add end, 2 show: "), scanf("%d", &choice))
{
switch(choice)
{
case 1:
AddEnd(&item, head);
break;
case 2:
printf("X = %d y= %d\n", item.x, item.y); /*prints 1 2*/
printf("x = %d y = %d\n", head->x, head->y); /*crash of program...should print 1 2*/
Show(head);
break;
default:
printf("TRY AGAIN\n");
break;
}
}
temp = head;
while(temp)
{
free(temp);
temp = head->next;
head = temp->next;
}
return 0;
}
void AddEnd(List * item, List * head)
{
List * node;
node = (List *)malloc(sizeof(List));
printf("Enter x and y: ");
scanf("%d %d", &node->x, &node->y);
if(head == NULL)
{
node->next = NULL;
head = node;
* item = * head;
}
else
{
item->next = node;
node->next = NULL;
}
}
void Show(List * head)
{
List * node;
node = head;
while(node)
{
printf("x = %d y = %d\n", node->x, node->y);
node = node->next;
}
}
尝试改变&节点 - >的x,&节点 - >在加数函数y到node.x&,&node.y 也头戴式> x至&head.x,头戴式> y以&head.y – 2013-03-20 06:38:56
请求成员x的东西不是一个结构或联盟 – balky 2013-03-20 06:44:49
但你有头=节点的功能,对吧,如果头== null – 2013-03-20 07:00:07