首页 > 解决方案 > 如何使用 C 更改我的 LinkedList 搜索节点代码

问题描述

我在 LinkedList 中搜索特定节点时遇到了一些问题。

老师教我怎么做,但是到家的时候忘记了,要改几行。

下面的代码是我自己做的作业。我认为主要问题是

listNode* searchNode 这里

温度=DL->头;

或者

搜索节点(m,o)?printf("是") : printf("否"); 这里。

我的 SearchNode 代码总是回答“否”。

我该如何解决?

抱歉英语不好。:(

#include <stdio.h>
#include <stdlib.h>
#include <string.h>  


typedef struct ListNode {
    int data;
    struct ListNode* link;
}listNode;

typedef struct {
    listNode* head;
} linkedList_h;

listNode* searchNode(linkedList_h* DL, int x) {
    listNode* temp;
    temp = DL->head;
    while (temp != NULL) {
        if (temp->data, x == 0) {
            return temp;
        }
        else {
            temp = temp->link;
        }
    }
    return temp;
}

void insertFirstListNode(linkedList_h* num, int data) {
    listNode* newNode = (listNode*)malloc(sizeof(listNode));
    newNode->link = num->head;
    newNode->data = data;
    num->head = newNode;
}

void insertLastNode(linkedList_h* num, int data) {
    listNode* newNode;
    listNode* temp;
    newNode = (listNode*)malloc(sizeof(listNode));
    newNode->data = data;
    newNode->link = NULL;
    if (newNode->link == NULL) {                            
        num->head = newNode;        
        return;
    }

    temp = num->head;
    while (temp->link != NULL) temp = temp->link;   
    temp->link = newNode;                            
}


linkedList_h* createLinkedList_h() {
    linkedList_h* Newlist = (linkedList_h*)malloc(sizeof(linkedList_h));
    Newlist->head = NULL;
    return Newlist;
}



void printList(linkedList_h* L) {
    listNode* p;
    printf("L = (");
    p = L->head;
    while (p != NULL) {
        printf("%d", p->data);
        p = p->link;
        if (p != NULL) printf(", ");
    }
    printf(") \n");
}


int main() {
    int i, j = 0;
    int k;
    int o = 0;

    linkedList_h* m;
    m = createLinkedList_h();
    insertLastNode(m, 4);
    printList(m);
    printf("size input\n");
    scanf_s("%d", &i);
    printf("%d\n", i);
    for (j = 0; j < i; j++) {
        printf("input \n");
        scanf_s("%d", &k);
        insertFirstListNode(m, k);
    }
    printList(m);
    printf("Find Nodes : ");
    scanf_s("%d", &o);
    printf("your Nodes : %d\n", o);
    searchNode(m, o) ? printf("yes") : printf("no");
    return 0;

}

标签: cdata-structureslinked-list

解决方案


该表达式temp->data, x == 0获取 的值temp->data并将其丢弃,然后x == 0在结果将用于条件的地方执行。

这意味着如果搜索的值是,您将只返回一个非空节点0,列表中的内容是不相关的(因为它没有在比较中使用)。然后它将始终返回列表中的第一个节点。

这真的没有意义。看来你想要的是temp->data == x


推荐阅读