【发布时间】:2013-10-25 22:29:15
【问题描述】:
这是我的代码,我正在尝试使用带有用户输入的菜单添加、打印、删除、清空列表,但它不保存或输出任何值。我通过调用循环外的函数对其进行了调试,它们可以工作,但问题是调用不会在循环内输出任何内容。
#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);
}
}
【问题讨论】:
-
我不明白对
Add、Delete等的一系列调用。它们在任何函数的主体之外。 -
显示一个示例会话并指出哪些结果是意外的。 “它不保存或输出任何值”不是对问题的有用描述。尽管您的麻烦可能与您从未在循环内调用
Add的事实有关。 -
@CareyGregory 这些调用应该修改一个包含值 3、20、55 的链表。添加,使用 void Add() 函数将数字添加到列表中,Delete() 从列表中删除数字。
-
但是在任何函数体之外,它们永远不会被执行。事实上,我很惊讶这段代码可以编译。
-
我可以在这里看到很多问题。为什么要在
do循环内重新声明head?你为什么要获取x的值却什么也不做?
标签: c pointers linked-list malloc