この連結リスト プログラムは 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;
}