我的代码需要一些帮助来覆盖存储在链接列表中的先前输入。这个项目比我这里的项目大得多,但在解决这个问题之前我无法继续。因此,假设用户输入“ins mom”“ins爸爸”“ins bob”,如果他们执行命令“prl”,它将打印出“bob bob bob”。它得到的节点数是正确的,但最后输入的 ins 命令总是填充列表并覆盖以前的内容。我花了一段时间尝试修复它,但仍然无法弄清楚。有人可以帮助我吗?
struct node{
char *symbol;
int count;
struct node *next;
};
int main(void){
void insert_node(struct node**,struct node**,char*,int);
void print_list(struct node*);
struct node *head,*tail;
char command[MAX];
char word[MAX];
int i = 1;
head = tail = NULL;
printf("Command? ");
scanf("%s",command);
if((strcmp(command,"prl")==0))
{
printf("The list is empty.");
printf("Command? ");
scanf("%s",command);
}
else{
scanf("%s",word);
}
while((strcmp(command,"end") != 0))
{
if((strcmp(command,"ins")== 0))
{
insert_node(&head,&tail,word,i);
}
printf("Command? ");
scanf("%s",command);
if((strcmp(command,"prl")==0))
{
print_list(head);
}
else{
scanf("%s",word);
}
}
return 0;
}
void insert_node(struct node**h,struct node**t,char w[],int c) //inserts string into the list
{
struct node *temp;
if((temp = (struct node *)malloc(sizeof(struct node))) == NULL){
printf("Node allocation failed. \n");
exit(1);
}
temp->count = c;
temp->symbol = w;
temp->next = NULL; //edited this in
if(*h == NULL)
{
*h = *t = temp;
}
else{
(*t)->next = temp; *t = (*t)->next;
}
}
void print_list(struct node *h){ //prints the list
if(h == NULL){
printf("The list is empty.\n");
}
else{
while(h != NULL)
{
printf("%d %s\n",h->count,h->symbol);
h = h->next;
}
}
}
最佳答案
首先,您应该意识到留出空间:
temp->symbol
而不仅仅是使用一个简单的等式将一个字符串插入另一个等式中。使用:
strcpy()
在为字符串分配内存之后。
其次,在打印函数中,应该打印除最后一个节点之外的所有节点,因为 while 循环将被终止。更好地检查你的代码,你会没事的:)
关于c - 链接列表输入被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7700238/