猿问

想要实现用单链表表示一个集合,元素类型为int且以递增方式储存的内容?该怎么做?

c语言题目,用单链表表示一个集合,元素类型为int且以递增方式储存,用函数in_set测试集合中是否存在元素0,若存在则结果输出0,反之输出1单链其头结点分别为a,b

忽然笑
浏览 218回答 3
3回答

梵蒂冈之花

#include<stdio.h>#include<stdlib.h>#include<time.h>#defineELEMTYPEinttypedefstructset{ELEMTYPEm;structset*next;}*NODE;NODEInitSet(){NODEhead=(NODE)malloc(sizeof(set));head->next=NULL;returnhead;}boolInsert(NODEhead,ELEMTYPEe){//创建增序链表NODEp,q;p=head;q=(NODE)malloc(sizeof(set));if(q==NULL)returnfalse;q->m=e;if(p->next==NULL){//直接插在头结点后q->next=NULL;p->next=q;returntrue;}while(p->next!=NULL){if(p->next->m==e)returnfalse;if(p->next->m>e){q->next=p->next;p->next=q;returntrue;}p=p->next;}if(p->next==NULL){//插在链表尾部p->next=q;q->next=NULL;}returntrue;}voidShowSet(NODEhead){NODEp=head->next;for(;p!=NULL;p=p->next)printf("%d",p->m);printf("\n");}boolInSet(NODEhead,ELEMTYPEe){NODEp=head->next;for(;p;p=p->next)if(p->m==e)returntrue;returnfalse;}boolIsEmpty(NODEhead){return(head->next==NULL);}intSetLength(NODEhead){intn=0;NODEp=head->next;for(;p;p=p->next)++n;returnn;}intmain(){NODEset=InitSet();inti,n;srand(time(NULL));n=rand()%100+1;for(i=0;i<30;++i)Insert(set,rand()%60+1);ShowSet(set);printf("该集合共有%d个人元素。\n",SetLength(set));if(InSet(set,n))printf("%d在集合中。\n",n);elseprintf("%d不在集合中。\n",n);return0;}

慕尼黑的夜晚无繁华

#include<stdio.h>#include<malloc.h>typedefstructNode{intdata;//数据域structNode*next;//指针域}Node,*LinkList;intin_set(LinkList*L,intn);intmain(){LinkListL;inti=1;L=(LinkList)malloc(sizeof(Node));printf("请输入集合整型元素(用空格隔开):\n");do{scanf("%d",&L->data);L=(LinkList)realloc(L,sizeof(Node)*++i);}while(getchar()!='\n');if(in_set(&L,i))printf("集合中存在0元素\n");elseprintf("集合中不存在0元素\n");}intin_set(LinkList*L,intn){inti;for(i=0;i<n;i++)if((*L)->data==0)//如果存在0元素,返回1return1;return0;//如果这条语句能够执行,说明不存在0元素}//程序我已经调试好了。集合元素你自己输入,想输入多少就输入多少,只要你的内存够大。输入以回车键结束。

慕慕森

#include#include#include#defineELEMTYPEinttypedefstructset{ELEMTYPEm;structset*next;}*NODE;NODEInitSet(){NODEhead=(NODE)malloc(sizeof(set));head->next=NULL;returnhead;}boolInsert(NODEhead,ELEMTYPEe){//创建增序链表NODEp,q;p=head;q=(NODE)malloc(sizeof(set));if(q==NULL)returnfalse;q->m=e;if(p->next==NULL){//直接插在头结点后q->next=NULL;p->next=q;returntrue;}while(p->next!=NULL){if(p->next->m==e)returnfalse;if(p->next->m>e){q->next=p->next;p->next=q;returntrue;}p=p->next;}if(p->next==NULL){//插在链表尾部p->next=q;q->next=NULL;}returntrue;}voidShowSet(NODEhead){NODEp=head->next;for(;p!=NULL;p=p->next)printf("%d",p->m);printf("\n");}boolInSet(NODEhead,ELEMTYPEe){NODEp=head->next;for(;p;p=p->next)if(p->m==e)returntrue;returnfalse;}boolIsEmpty(NODEhead){return(head->next==NULL);}intSetLength(NODEhead){intn=0;NODEp=head->next;for(;p;p=p->next)++n;returnn;}intmain(){NODEset=InitSet();inti,n;srand(time(NULL));n=rand()%100+1;for(i=0;i<30;++i)Insert(set,rand()%60+1);ShowSet(set);printf("该集合共有%d个人元素
随时随地看视频慕课网APP
我要回答