当前位置:   article > 正文

已给单链表的头指针为h,每个节点的数据域data为整型,指针域为next,设计一个算法inserta(H,d),实现若d已在链表中,则输出‘已存在’,然后返回,否则将d插入到链表的最后_求头指针为head的单循环链表中data域值为正整数

求头指针为head的单循环链表中data域值为正整数
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct Node    //创建链表 
{
    int data;
	struct Node *next;	
}List;

void InputList(List *);    //初始化函数声明 
int Inserta(List *,int);    //查找或添加声明 

main()
{
	int d;
	List *h;
	h=(List *)malloc(sizeof(List));
	InputList(h);    //初始化函数       
	while(1)    //循环查找或添加 
	{
	printf("请输入要查找的点:\n");
	scanf("%d",&d);    //要查找的结点值域为d 
	Inserta(h,d);
	}
	return 0;
}

void InputList(List *H)
{
    int i,n,a;
    List *p,*q;
    p=H;
	printf("请输入结点数量:\n");
	scanf("%d",&n);
	//H->data=n;    //把结点数量保存在头结点里,此程序可有可无 
	for(i=0;i<n;i++)
	{
		q=(List *)malloc(sizeof(List));
		printf("请为第%d个结点赋值:\n",i+1);
		scanf("%d",&a);
		q->data=a;
		q->next=NULL;
		p->next=q;
		p=q;			
	}	
} 

int Inserta(List *H,int d)
{
	List *p,*q;
	p=H->next;    //p指向首元结点 
	while(p->next!=NULL)    //当p的指针域不为空时     当结束该while循环时,p指向末节点,但没有遍历末节点 
	{
		if(p->data==d)                                //不遍历末节点有一个好处,可以让 p 刚好指向末节点,方便后序插入 
		{
			printf("存在\n");
			return 0;
		}
		else	
			p=p->next;   //p指向下一个结点 
	}
	if(p->data==d)    //因为末节点未被遍历,补充末节点的遍历 
	{
		printf("存在\n");
	}
	else	
	{
		printf("不存在,尾部加入该新结点\n");    //在末节点 p 后插入新结点 
		q=(List *)malloc(sizeof(List));
		q->data=d;
		q->next=NULL;
		p->next=q;
	}
	return 0;	
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/466983
推荐阅读
相关标签
  

闽ICP备14008679号