微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C语言链表中的节点 # 创建名为 Word 的结构体,具有字符名称[100]# 创建名为 Node 的结构体# 可以将节点插入到列表的第一个的函数# 可以打印列表的函数# 可以搜索单词的函数条件语句不起作用但没有错误# int main()

如何解决C语言链表中的节点 # 创建名为 Word 的结构体,具有字符名称[100]# 创建名为 Node 的结构体# 可以将节点插入到列表的第一个的函数# 可以打印列表的函数# 可以搜索单词的函数条件语句不起作用但没有错误# int main()

我开始学习链表。 我的问题是条件语句不起作用。这是问题代码

'''
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,"BANANA");
head = insert_first(head,"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

感谢您阅读令人眼花缭乱的代码

解决方法

在这个 if 语句中

if(p->data.name==target.name)

比较两个指针(在将数组指示符隐式转换为指向它们的第一个元素的指针之后)而不是指针指向的字符串。

你需要写

if( strcmp( p->data.name,target.name ) == 0 )

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。