1--在主函数中遍历:
应该就一个关键点,即是使用p!=NULL还是p->next!=NULL。
还有就是for循环的妙用。
--main.h--
#ifndef _MAIN_H_
#define _MAIN_H_
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int value;
struct node *next;
}node;
#endif
--main.c--
#include "main.h"
//typedef struct node{
// int value;
// struct node *next;
//}node;
void add(node** head,node** tail,int number);
int main(int argc,char const *argv[]){
int number=0;
node *head;
node *tail;
head=tail=NULL;
while(number!=-1)
{
scanf("%d",&number);
if (number!=-1)
{
add(&head,&tail,number);
}
}
node *p;
for (p=head;p;p=p->next)
{
printf("%d ",p->value);
}
printf("\n请输入要查找的值\n");
int x;
scanf("%d",&x);
int nu=0;
for (p=head;p;p=p->next)
{
if (p->value==x)
{
nu=1;
break;
}
}
if (nu==0)
{
printf("notfound");
}
else
{
printf("haven found");
}
return 0;
}
void add(node** head,node** tail,int number)
{
node *p=(node*)malloc(sizeof(node));
p->next=NULL;
p->value=number;
node *k=*head;
if (k==NULL)
{
*head=p;
*tail=p;
}
else
{
(*tail)->next=p;
*tail=p;
}
}
2--在函数中遍历输出查找:
遍历输出时,因为只是输出,所以传一级指针即可。
要查找时,也只需传一级指针。
--main.c--
#include "main.h"
//typedef struct node{
// int value;
// struct node *next;
//}node;
void add(node** head,node** tail,int number);
void printff(node *head);
void search(node *head);
int main(int argc,char const *argv[]){
int number=0;
node *head;
node *tail;
head=tail=NULL;
while(number!=-1)
{
scanf("%d",&number);
if (number!=-1)
{
add(&head,&tail,number);
}
}
printff(head);
search(head);
return 0;
}
void add(node** head,node** tail,int number)
{
node *p=(node*)malloc(sizeof(node));
p->next=NULL;
p->value=number;
node *k=*head;
if (k==NULL)
{
*head=p;
*tail=p;
}
else
{
(*tail)->next=p;
*tail=p;
}
}
void printff(node *head)
{
node *p=head;
for (p=head;p;p=p->next)
{
printf("%d ",p->value);
}
}
void search(node *head)
{
node *p=head;
int nu=0;
printf("\n请输入你要查找的值\n");
int x;
scanf("%d",&x);
for (p=head;p;p=p->next)
{
if (p->value==x)
{
nu=1;
break;
}
}
if (nu==0)
{
printf("notfound");
}
else
{
printf("found成功");
}
}