我想构建只有 add_to_end 和 show_list 函数的链表,但是当我想显示时我的列表崩溃了,head
虽然item
有效(查看代码)。
#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;
}
}