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

时间:2015-12-04 00:00:51

标签: c list pointers linked-list function-pointers

我正在尝试计算给定int在列表中出现的次数,但是我很难让我的指针工作。有人能发现我的逻辑失败了吗?是因为我正在实施“跟随”“ - >”在计数功能?

//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;
}

2 个答案:

答案 0 :(得分:2)

你的问题是在while循环中 你是一个列表结构,然后你做 电流 - >前置式>接着, 现在你处于NODE类型结构中,在下一次迭代中,NODE中没有前端。 enter image description here

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

答案 1 :(得分:0)

由于你的所有建议,我得到了功能

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