我用 C 创建了这个链表程序。它从 a3data.txt 中读取数据(这个文本文件的内容粘贴在输出之后,如下所示)。在文本文件中,INSERT 和 REMOVE 是命令。我希望能够读取命令 INSERT,并将下一个整数(下一行)插入到列表中。REMOVE 命令应该从列表中删除最后一个节点。如您所见,我的删除功能无法正常工作,我不明白为什么。有人可以帮我调试一下吗?
输出
linux@computer ~/Documents/Data Structures/a3/code $ gcc exercise4.3.3.c
linux@computer ~/Documents/Data Structures/a3/code $ ./a.out
INSERT 0 5
INSERT 0 5 3
INSERT 0 5 3 19
REMOVE 0 5 3 19
INSERT 1
REMOVE 0
REMOVE 0
REMOVE 0
INSERT 4
INSERT 4 25
INSERT 4 25 5
REMOVE 0 25 5
INSERT 4
INSERT 4 874
REMOVE 0 874
REMOVE 0 874
INSERT 8
INSERT 8 75
INSERT 8 75 22
INSERT 8 75 22 6
REMOVE 0 75 22 6
INSERT 9
INSERT 9 31
INSERT 9 31 1
REMOVE 0 31 1
REMOVE 0 31 1
INSERT 419
INSERT 419 55
REMOVE 0 55
INSERT 5
文本文件
INSERT
5
INSERT
3
INSERT
19
REMOVE
INSERT
1
REMOVE
REMOVE
REMOVE
INSERT
4
INSERT
25
INSERT
5
REMOVE
INSERT
4
INSERT
874
REMOVE
REMOVE
INSERT
8
INSERT
75
INSERT
22
INSERT
6
REMOVE
INSERT
9
INSERT
31
INSERT
1
REMOVE
REMOVE
INSERT
419
INSERT
55
REMOVE
INSERT
5
代码
#include <stdio.h>
#include <stdlib.h>
struct node {
int number;
struct node *next;
};
/* prototypes */
void ins(struct node *llist, int number);
void rem(struct node *llist);
void sho(struct node *llist);
int main(void)
{
int number;
char command[6];
struct node *llist;
llist = (struct node *)malloc(sizeof(struct node));
llist->number = 0;
llist->next = NULL;
FILE *file;
file = fopen("a3data.txt", "r");
if (file == NULL)
{
printf("\n----------------------------------------\n");
printf("| Error. Did not read file. Exiting. |\n");
printf("----------------------------------------\n\n");
exit(1);
}
else
{
while ((fscanf(file, "%s", command)) != EOF)
{
if((strcmp(command, "INSERT"))==0)
{
fscanf(file, "%d", &number);
printf("\nINSERT ", number);
ins(llist, number);
sho(llist);
}
else if((strcmp(command, "REMOVE"))==0)
{
printf("\n REMOVE ");
rem(llist);
sho(llist);
}
}
}
printf("\n");
free(llist);
return(0);
}
void ins(struct node *llist, int number)
{
while(llist->next != NULL)
{
llist = llist->next;
}
llist->next = (struct node *)malloc(sizeof(struct node));
llist->next->number = number;
llist->next->next = NULL;
}
void rem(struct node *llist)
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
/* remove the node */
temp = llist->next;
free(llist);
llist = temp;
}
void sho(struct node *llist)
{
while(llist->next != NULL)
{
printf("%d ", llist->number);
llist = llist->next;
}
printf("%d", llist->number);
}
尝试解决方案(我认为它适用于 LIFO)
void rem(struct node *llist)
{
while(llist->next->next != NULL)
{
llist = llist->next;
}
llist->next = NULL;
}