【发布时间】:2019-12-09 14:20:43
【问题描述】:
我在 LinkedList 中搜索特定节点时遇到了一些问题。
老师教我怎么做,但是到家的时候忘记了要改几行的东西。
下面的代码是我自己做的功课。 我认为主要问题是
listNode* 在此处搜索节点
temp = DL->head;
或
searchNode(m, o) ? printf("yes") : printf("no");在这里。
我的 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;
}
【问题讨论】:
-
作为风格问题,您可能应该检查 searchNode 以查看它是否为空,而不是依赖于零等效。
while(x)可以,但是 C 标准定义了 0 强制转换为 void * 类型既是空指针又是空指针常量。那是相当遥远的地方;请改用searchNode != NULL。它使事情变得更加清晰。 -
if (temp->data, x == 0)应该做什么?您很可能在这里误用了逗号运算符。 -
@Jabberwocky 现在我明白了,那是我的错误。教授教我“Char”,但作业是给“Int”的
标签: c data-structures linked-list