链表的遍历输出和搜索

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成功");
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值