计算 int 在列表中出现次数的函数错误

error in function that counts the number of times an int appears in a list

我正在尝试计算给定 int 在列表中出现的次数,但我很难让我的指针起作用。有人可以发现我的逻辑在哪里失败吗?是因为我如何在计数函数中实现 "follows"“->”吗?

//this is in my .h file
typedef struct list_struct LIST;

///// the rest is in my .c file
typedef struct node {
ElemType val;
struct node *next;
} NODE;

struct list_struct {
NODE *front;
NODE *back;
};

//this is my counting function
int lst_count(LIST *l, ElemType x) {
  LIST *current = l;
  int count = 0;

  while (current != NULL) {
      if ((current->front->val) == x) count++;
      current = current->front->next; 
      //in the line above I get the following warning:
      //"incompatible pointer types assigning to 'LIST*' (aka 'struct list_struct*') from 'struct node*'"
  }
  return count;
}

你的问题出在while循环中 你在一个列表结构中,然后你做 当前->前面->下一个; 现在您处于 NODE 类型结构中,在下一次迭代中,NODE 中没有前面。

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

typedef struct node {
    int val;
    struct node *next;
    struct node *previous;
} NODE;


int lst_count(NODE *l, int x) {
  NODE *current = l;
  NODE *start = current; /* so that we wont loose the start*/
  int count = 0;
  while (current != NULL) {
      if ((current->val) == x)
        count++;
      current = current->next;
  }
  return count;
}

int main()
{
    NODE* p = (NODE*)malloc(sizeof(NODE));
    NODE* p1 = (NODE*)malloc(sizeof(NODE));
    NODE* p2 = (NODE*)malloc(sizeof(NODE));
    NODE* start = p;
    p->val = 5;
    p->next = p1;
    p1->next = p2;
    p2->next=NULL;
    p1->val = 5;
    p2->val = 5;
    printf("%d", lst_count(start, 5));
 }

感谢大家的建议,我的功能可以正常工作了

int lst_count(LIST *l, int x) {
   NODE *current = l->front;
   int count = 0;

   while (current != NULL) {
      if ((current->val) == x) count++;
      current = current->next;
   }
   return count;
}