资源描述:
《数据结构编程实例》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、数据结构编程实例1.顺序表的基本操作#defineLEN100typedefstructsqlist{inta[LEN];intlength;};voidinit(structsqlist*sq)/*初始化*/{inti;for(i=0;ia[i]=0;sq->length=0;}voidcreat(structsqlist*sq)/*建顺序表*/{inti;printf("pleaseinputlength");scanf("%d",&sq->length);printf("pleaseinpu
2、t%dnums",sq->length);for(i=1;i<=sq->length;i++)scanf("%d",&sq->a[i]);}voidprint(structsqlist*sq)/*输出顺序表*/{inti;for(i=1;i<=sq->length;i++)printf("%d",sq->a[i]);printf("");}voidinsert(structsqlist*sq,intpos,intx)/*顺序表插入元素*/{inti;for(i=sq->length;i>=pos;i--)sq->a
3、[i+1]=sq->a[i];sq->a[pos]=x;sq->length=sq->length+1;}intdelete(structsqlist*sq,intpos)/*顺序表删除元素*/{inti,x;x=sq->a[pos];for(i=pos+1;i<=sq->length;i++)sq->a[i-1]=sq->a[i];sq->length=sq->length-1;return(x);}main(){intposition,x;structsqlist*list;structsqlistslist;intx
4、z=0;list=&slist;while(1){printf("1.init");printf("2.creat");printf("3.insert");printf("4.delete");printf("5.locate_value");printf("6.locate_pos");printf("7.print");printf("0.exit");printf("pleaseinputyourchoice");scanf("%d",&xz);switch(xz){case1:in
5、it(list);break;case2:creat(list);break;case3:printf("pleastinputinsetposition(pos)andvalue(x)");scanf("%d%d",&position,&x);if(position<1
6、
7、position>list->length+1
8、
9、list->length>=LEN)printf("positionerror");elseinsert(list,position,x);break;case4:printf("pleastinp
10、utdeleteposition(pos)");scanf("%d",&position);if(position<1
11、
12、position>list->length
13、
14、list->length==0)printf("positionerror");elseprintf("deleteposition=%d,deletedata=%d",position,delete(list,position));break;;case5:;case6:;case7:print(list);break;case0:exit(0);
15、}}}1.三种方法建立链表#includetypedefstructnode{intdata;structnode*link;}NODE;NODE*creat1()/*按输入数据的顺序建立链表,输入数据通过个数控制*/{inti,data,n;NODE*h=NULL,*p,*last=NULL;printf("pleaseinputthenum:");scanf("%d",&n);printf("pleaseinput%ddatas:",n);for(i=1;i<=n;i++){p=(NODE*)mall
16、oc(sizeof(NODE));scanf("%d",&p->data);if(i==1)h=p;elselast->link=p;last=p;}last->link=NULL;return(h);}NODE*creat2()/*按输入数据的逆序建立链表,输入数据以0结束*/{intdata;NOD