这是我的代码,我正在尝试使用带有用户输入的菜单添加、打印、删除、清空列表,但它不保存或输出任何值。我通过调用循环外的函数对其进行了调试,它们可以工作,但问题是调用不会在循环内输出任何内容。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int Length(struct node* head);
void PrintList(struct node* head);
void Add(struct node** headRef, int new );
int Delete(struct node** headRef);
void ZeroList(struct node** headRef);
int main(void) {
struct node * head = NULL;
char enter;
int x;
Add( &head, 13 );
printf("\na(add){x}\nd(del)\nl(ength)\np(rint)\nz(ero)\ne(xit)");
do
{
fscanf(stdin, "%c", &enter);
struct node *head = NULL;
switch (enter)
{
case 'a':
printf("Enter a node: ");
fscanf(stdin,"%d", &x);
Add(&head, x);
break;
case 'd':
printf("Delete\n");
Delete(&head);
break;
case 'l':
printf("Length");
Length(head);
break;
case 'p':
printf("printList");
PrintList(head);
break;
case 'z':
printf("ZeroList");
ZeroList(&head);
break;
}
}while (enter != 'e');
Add(&head, 23);
PrintList(head);
return 0;
}
//Debug
/* Add( &head, 3 );
Add( &head, 20 );
Add( &head, 55 );
Delete(&head);
Length(head);
PrintList(head);
ZeroList(&head);
PrintList(head);*/
int Length(struct node* head) {
struct node *current = head;
int count = 0;
while (current != NULL)
{
count++;
current = current->next;
}
printf(" Size of head is %d\n", count);
return(count);
}
void PrintList(struct node* head) {
struct node *current = head;
while (current != NULL)
{
printf("printing %d\n", current->data);
current = current->next;
}
}
void Add(struct node** headRef, int new) {
struct node *k = malloc(sizeof(struct node));
k->data = new;
k->next = *headRef;
*headRef = k;
return;
}
int Delete(struct node** headRef) {
struct node* current = *headRef;
if (current == NULL)
{
printf("List is empty!\n");
}
else
{
printf("Deleted value is: %d\n", current->data);
*headRef = current->next;
free(current);
}
return 0;
}
void ZeroList(struct node** headRef){
struct node* current = *headRef;
while (current != NULL)
{
current = current->next;
free(current);
}
}