我需要一些帮助,用我的代码覆盖存储在我的链接列表中的以前的输入。这个项目比我在这里的要大得多,但我不能继续下去,直到我解决这个问题。因此,如果用户输入“ins妈妈”,“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;
}
}
}
什么是'h'?正如'* h = * t = temp;'? –
@Lasse V. Karlsen我认为它应该被理解为“如果头是空的”(空列表),然后将头部尾部和尾部设置为温度,因此它是一个循环链表。 – dcousens
是的,如果head最初是null,那么head和tail都指向temp,因为列表只有一个节点长。 – user985843