gpt4 book ai didi

C 链表查找函数

转载 作者:行者123 更新时间:2023-11-30 21:34:52 25 4
gpt4 key购买 nike

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

/*Define custom functions */
void insertElement();
bool elementExists();
int getNumElements();


/*Create linked list */
struct node {
int number;
int occurence;
struct node *next;
};

/*Call our linked list freqTable */
struct node *freqTable = NULL;

unsigned int numElements = 0;

int main(){
int readNumElements = 0;
int i = 0;
int newNum, status;

status = scanf("%d", &readNumElements);
if(status == -1){
fprintf(stderr, "%d is not a number\n", readNumElements);
exit(-1);
}


for (i = 0; i < readNumElements;i++) {
status = scanf("%d", &newNum);
if(status == -1){
fprintf(stderr, "%d is not a number\n", newNum);
exit(-1);
}
if(elementExists(newNum)){
printf("%d exists\n", newNum);
}else{
insertElement(&freqTable, newNum);
}

}

return 0;
}

void insertElement(struct node **list, int n){
struct node *new_input;

new_input = malloc(sizeof(struct node));

if(new_input == NULL){
fprintf(stderr,"Error: Failed to create memory for new node\n");
exit(EXIT_FAILURE);
}

new_input->number = n;
new_input->occurence = 1;
new_input->next = *list;
numElements++;

*list = new_input;
}

bool elementExists(int n){
printf("%d\n", freqTable->number);
return false;
}

int getNumElements(){
return numElements;
}

好的,这就是我得到的。这应该可以编译。

问题出现在

    if(elementExists(newNum)){
printf("%d exists\n", newNum);
}else{
insertElement(&freqTable, newNum);
}

我收到段错误,但我不知道为什么。

最佳答案

在函数 elementExists 中,您需要确保 freqTable 不为 NULL :

bool elementExists(int n){
if(freqTable) { // add this check
printf("%d\n", freqTable->number);
}
}

此外,您的 elementExists 也没有执行其应该执行的操作(检查是否存在值为 n 的节点),您应该执行以下操作:

bool elementExists(int n) {

if(!freqTale) { // table does not exist..return false.
return false;
}
// table exists..iterate node by node and check.
struct node *tmp = freqTable;
while(tmp) { // loop till tmp becomes NULL
if(*tmp == n) { // it node contains n..return false.
return true;
}
tmp = tmp->next; // move on
}
return false; // n does not exist in the list..return false.
}

关于C 链表查找函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3792348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com