C 链表查找函数

标签 c search linked-list

#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/

相关文章:

java - 从 Cracking the Coding Interview 中删除列表中的重复项

将 C 代码编译为动态链接库

c - 交易前后的sqlite差异

c - 陷入 C 词典项目

php - 基于相同关键字显示结果的 SQL 查询

php - mysql+php 中匹配相似列表

c++ - 如何在 C++ 中打印出以下实现的链表?

c - 我找不到编译器中指出的函数

algorithm - 深度受限搜索递归伪代码

java - 如何将LinkedList中具有多种行为的行为显示在一行中