【发布时间】:2021-07-06 19:05:40
【问题描述】:
我开始学习链表。 我的问题是条件语句不起作用。这是问题代码。
'''
Node* search_word(Node* head, Word target)
{
Node*p=head;
while(p != NULL)
{
if(p->data.name==target.name)
{
printf("%s founded", target.name);
return p;
};
p=p->nextNodeAddress;
};
printf("There is no %s. \n", target.name);
return NULL;
}
'''
这是我的完整源代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
# 创建名为 Word 的结构体,其字符名称为 [100]
typedef struct Word
{
char name[100];
} Word;
# 创建名为 Node 的结构体
typedef struct node
{
Word data;
struct node* nextNodeAddress;
} Node;
# 可以将节点插入列表第一个的函数
Node* insert_first(Node*head, Word newData)
{
Node* p=(Node*)malloc(sizeof(Node));
p->data = newData;
p->nextNodeAddress=head;
head=p;
return head;
};
#可以打印出列表的函数
void print_listedNode(Node* head)
{
for(Node* i=head; i!=NULL; i=i->nextNodeAddress)
{
printf("%s->", i->data.name);
};
printf("NULL\n");
}
# 可以搜索单词的函数(条件语句不起作用。但没有错误。)
Node* search_word(Node* head, Word target)
{
Node*p=head;
while(p != NULL)
{
if(p->data.name==target.name)
{
printf("%s founded", target.name);
return p;
};
p=p->nextNodeAddress;
};
printf("There is no %s. \n", target.name);
return NULL;
}
# int main()
int main(int argv, char* argc)
{
Node* head = NULL;
Word data;
strcpy(data.name, "APPLE");
head = insert_first(head, data);
print_listedNode(head);
strcpy(data.name, "LEMON");
head = insert_first(head, data);
print_listedNode(head);
strcpy(data.name, "BANANA");
head = insert_first(head, data);
print_listedNode(head);
strcpy(data.name, "BANANA");
head = search_word(head, data);
print_listedNode(head);
return 0;
}
结果是
APPLE->NULL
LEMON->APPLE->NULL
BANANA->LEMON->APPLE->NULL
There is no BANANA.
NULL
我希望得到
APPLE->NULL
LEMON->APPLE->NULL
BANANA->LEMON->APPLE->NULL
BANANA founded
BANANA->LEMON->APPLE->NULL
感谢您阅读令人眼花缭乱的代码。
【问题讨论】:
-
您正在使用
p->data.name==target.name,这在C中不起作用。它会比较那里的指针。使用函数strncmp。 -
@Hrant 不,应该在这里使用
strcmp而不是strncmp。
标签: c string-comparison c-strings function-definition