c - 如何使用 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;
}
解决方案
该表达式temp->data, x == 0
获取 的值temp->data
并将其丢弃,然后x == 0
在结果将用于条件的地方执行。
这意味着如果搜索的值是,您将只返回一个非空节点0
,列表中的内容是不相关的(因为它没有在比较中使用)。然后它将始终返回列表中的第一个节点。
这真的没有意义。看来你想要的是temp->data == x
。
推荐阅读
- python - 如何通过字符串变量迭代读取 Pandas Dataframe 列信息
- string - 如何将索引开始到文本文件中的不同位置?
- data-binding - 当值为“”Angular 6时从对象中删除一个属性
- r - 如何在有条件的情况下使用 expand.grid?
- google-cloud-functions - Firebase 图片调整大小扩展的问题
- c# - 如何使用 for each 将多个对象添加到数据库中
- reactjs - 通过事件处理程序将组件添加到渲染树,该组件似乎没有收到新的道具。为什么是这样?
- c# - 将数据绑定到 Datagridview 的特定列 - 实体框架
- firebase - Flutter with firebase 试图在与我的登录屏幕不同的屏幕或小部件上访问当前用户
- c++ - 尝试使用 gcc 构建 pybind11 项目时获取未定义的引用