我试图计算一个给定的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循环中
你在列表结构中,然后
当前->前->下一步;
现在您处于节点类型结构中,在下一次迭代中,节点中没有前端。
c - 函数错误,该错误计算int在列表中出现的次数-LMLPHP

#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));
 }

09-09 18:37