关于#链表#的问题,如何解决?

单链表查找值

#include
using namespace std;
struct node
{
int num;
node *next;
};
void set_ahead(node *head)
{
int n;
cin>>n;
while(n--)
{
node *p=new node;
cin>>p->num;
p->next=head->next;
head->next=p;
}
node *tmp=head->next;
while(n--)
{
cout<num<<' ';
tmp=tmp->next;
}
}
void found(node *head)
{
int goal;
cin>>goal;
node *pt=head->next;
while(pt)
{
if(pt->num==goal)
cout<<"Found!"<<endl;
else
pt=pt->next;
}
cout<<"Not found!"<<endl;
}
int main()
{
node *head=new node;
set_ahead(head);
found(head);
return 0;
}

img

为啥无法执行found函数,求帮忙看看,谢谢!

set head中第二个n-- 的n没有初始化


#include <iostream>
using namespace std;


struct node
{
    int num;
    node *next;
};
void set_ahead(node *head)
{
    int n;
    cin >> n;

    while(n--)
    {
        node *p = new node;
        cin >> p->num;
        p->next = head->next;
        head->next = p;        
    }

    node *tmp = head->next;

    while(tmp)//while(n--)
    {
        cout << tmp->num << ' ';//cout < num << ' ';  
        tmp = tmp->next;
    }
}
void found(node *head)
{
    int goal;
    cin >> goal;
    node *pt = head->next;

    while(pt)
    {
        if(pt->num == goal)
        {
            cout << "Found!" << endl;
            return;//
        }
        else
            pt = pt->next;
    }

    cout << "Not found!" << endl;
}
int main()
{
    node *head = new node;
    head->next=NULL;//

    set_ahead(head);
    found(head);

    return 0;
}