【发布时间】:2011-10-08 22:43:02
【问题描述】:
我需要一些帮助,以便我的代码覆盖之前存储在我的链接列表中的输入。这个项目比我在这里的要大得多,但在我弄清楚这个问题之前我不能继续。因此,假设用户输入“ins mom”“ins dad”“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 我认为它应该被解读为“如果 head 为空”(空列表),然后将 head 设置为 tail,tail 设置为 temp,因此它是一个循环链表。
-
是的,如果 head 最初为 null,那么 head 和 tail 都指向 temp,因为列表只有一个节点长。
标签: c list linked-list