这个计数链表有什么问题

whats wrong with this linked list for counting

本文关键字:什么 问题 链表      更新时间:2023-10-16

TH以下代码崩溃,我不确定为什么。尝试计算在以下链表中找到整数的次数。然而 xcode 一直说 int count=0 从主正在破坏线程?

 #include <iostream>  
 using namespace std;
struct Node {
  int val;
  Node *next;
};

  int countNum (Node *head, int key);
  Node* cons (int x, Node* p);
   int main()
   {
     Node *head = (1,cons(2,cons(2,(cons(4,(cons(5,nullptr)))))));
     int counts=0;
     counts= countNum(head,2);
     cout<< counts<< head;
     return 0;
 }
  Node* cons (int x, Node* p){
        Node *q=new Node;
        q->val=x;
        q->next=p;
    return p;
 }
 int countNum (Node *head, int key) {
         int count=0;
        if (head==nullptr)
             return 0;
         Node *follow=head;
          while (follow!=nullptr) {
                if(follow->val==key)
                   count++;
                follow=follow->next;
          }
            cout<<count;
           return count;
    }

使用 Node *head = cons(1,cons(2,cons(2,(cons(4,(cons(5,nullptr))));

我认为您想返回指向当前节点而不是下一个节点的指针。另外,我认为您不能这样做:

Node *head = (1, ptrToNextNode);

像这样的东西可能会起作用:

struct Node *head = malloc(sizeof (struct Node));
head->value = 1;
head->next = cons(2,cons(2,(cons(4,(cons(5,nullptr))))));

Node* cons (int x, Node* p)
{
    Node *q=new Node;
    q->val=x;
    q->next=p;
    return q;
}