数据结构上机实验答案
数据结构实验上机题答案

实验一#include<stdio.h>#include<malloc.h>#define OK 1#define ERROR 0#define LIST_INIT_SIZE 100#define LISTINCREMENT 10#define ElemType inttypedef struct{int *elem,length,listsize;}SqList;int InitList_Sq(SqList &L){L.elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));L.length=0;L.listsize=LIST_INIT_SIZE;return OK;}int Load_Sq(SqList &L){int i;if(L.length==0)printf("The List is empty!");else{printf("The List is:");for(i=0;i<L.length;i++)printf("% d",L.elem[i]);}printf("\n");return OK;}int ListInsert_Sq(SqList &L,int i,int e) {if(i<1||i>L.length+1)return ERROR;ElemType *newbase,*q,*p;if(L.length>=L.listsize){newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*size of(ElemType));L.elem=newbase;L.listsize+=LISTINCREMENT;}q=&(L.elem[i-1]);for(p=&(L.elem[L.length-1]);p>=q;--p)*(p+1)=*p;*q=e;++L.length;return OK;}int ListDelete_Sq(SqList &L,int i,int &e){ElemType *q,*p;if(i<1||i>L.length)return ERROR;p=&(L.elem[i-1]);e=*p;q=L.elem+L.length-1;for(++p;p<=q;p++)*(p-1)=*p;L.length--;return OK;}int main(){SqList T;int a,i;ElemType e,x;if(InitList_Sq(T)){printf("A Sequence List Has Created.\n");}while(1){printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n");scanf("%d",&a);switch(a){case 1: scanf("%d%d",&i,&x);if(!ListInsert_Sq(T,i,x))printf("Insert Error!\n");elseprintf("The Element %d is Successfully Inserted!\n",x);break;case 2: scanf("%d",&i);if(!ListDelete_Sq(T,i,e))printf("Delete Error!\n");elseprintf("The Element %d is Successfully Deleted!\n",e);break;case 3: Load_Sq(T);break;case 0: return 1;}}} 222222222222222222222222222222222222222222222222222222222222222222222222222222#include<stdio.h>#include<malloc.h>#define OK 1#define ERROR 0#define LIST_INIT_SIZE 100#define LISTINCREMENT 10#define ElemType inttypedef struct{int *elem,length,listsize;}SqList;int InitList_Sq(SqList &L){L.elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));L.length=0;L.listsize=LIST_INIT_SIZE;return OK;}int Load_Sq(SqList &L){int i;for(i=0;i<L.length;i++)printf("%d ",L.elem[i]);printf("\n");return OK;}int ListLength(SqList L){return L.length;}int GetElem(SqList L,int i,ElemType &e) {e=L.elem[i-1];return OK;}int ListInsert_Sq(SqList &L,int i,int e) {if(i<1||i>L.length+1)return ERROR;ElemType *p,*q,*newbase;if(L.listsize<=L.length){newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*size of(ElemType));L.elem=newbase;L.listsize+=LISTINCREMENT;}q=&(L.elem[i-1]);for(p=&(L.elem[L.length-1]);p>=q;p--)*(p+1)=*p;*q=e;L.length++;return OK;}void MergeList(SqList La,SqList Lb,SqList &Lc){int i,j,k,La_len,Lb_len,ai,bj;i=j=1;k=0;InitList_Sq(Lc);La_len=ListLength(La);Lb_len=ListLength(Lb);while((i<=La_len)&&(j<=Lb_len)) {GetElem(La,i,ai);GetElem(Lb,j,bj);if(ai<=bj){ListInsert_Sq(Lc,++k,ai);i++;}else{ListInsert_Sq(Lc,++k,bj);j++;}}while(i<=La_len){GetElem(La,i++,ai);ListInsert_Sq(Lc,++k,ai);}while(j<=Lb_len){GetElem(Lb,j++,bj);ListInsert_Sq(Lc,++k,bj);}Load_Sq(Lc);}int main(){int an,bn,i,e;SqList La,Lb,Lc;InitList_Sq(La);scanf("%d",&an);for(i=1;i<=an;i++){scanf("%d",&e);ListInsert_Sq(La,i,e);}printf("List A:");Load_Sq(La);InitList_Sq(Lb);scanf("%d",&bn);for(i=1;i<=an;i++){scanf("%d",&e);ListInsert_Sq(Lb,i,e);}printf("List B:");Load_Sq(Lb);printf("List C:");MergeList(La,Lb,Lc);return 0;}3333333333333333333333333333333333333333333333333333333333 33333333333333333333#include<stdio.h>#include<malloc.h>#define OK 1#define ERROR 0#define LIST_INIT_SIZE 100#define LISTINCREMENT 10#define ElemType inttypedef struct{int *elem,length,listsize;}SqList;int InitList_Sq(SqList &L){L.elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));if(!L.elem){printf("NO1");return ERROR;}L.length=0;L.listsize=LIST_INIT_SIZE;return OK;}int Load_Sq(SqList &L){int i;if(!L.length){printf("This List is empty!\n");return ERROR;}else{for(i=0;i<L.length;i++)printf("%d ",L.elem[i]);}printf("\n");return OK;}int ListInsert_Sq(SqList &L,int i,int e) {ElemType *newbase,*p,*q;if(L.length>=L.listsize){newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*size of(ElemType));if(!newbase){printf("NO2");return ERROR;}L.elem=newbase;L.listsize+=LISTINCREMENT;}q=&(L.elem[i-1]);for(p=&(L.elem[L.length-1]);p>=q;p--)*(p+1)=*p;*q=e;L.length++;return OK;}int swap(SqList &L,int n){int i,j,temp;for(i=0,j=n-1;j>i;i++,j--){temp=L.elem[i];L.elem[i]=L.elem[j];L.elem[j]=temp;}return OK;}int main(){SqList T;int n,i;ElemType x;scanf("%d",&n);InitList_Sq(T);for(i=1;i<n+1;i++){scanf("%d",&x);ListInsert_Sq(T,i,x);}printf("The List is:");Load_Sq(T);swap(T,n);printf("The turned List is:");Load_Sq(T);return 0;}4444444444444444444444444444444444444444444444444444444444 44444444444444444444#include<stdio.h>#include<malloc.h>#define ERROR 0#define OK 1#define ElemType inttypedef struct LNode{int data;struct LNode *next;}LNode,*LinkList;int CreateLink_L(LinkList &L,int n){LinkList p,q;int i;ElemType e;L=(LinkList)malloc(sizeof(LNode));L->next=NULL;q=(LinkList)malloc(sizeof(LNode));q=L;for(i=0;i<n;i++){scanf("%d",&e);p=(LinkList)malloc(sizeof(LNode));p->data=e;p->next=q->next;q->next=p;q=q->next;}return OK;}int LoadLink_L(LinkList &L){LinkList p=L->next;if(!p)printf("The List is empty!");else{printf("The LinkList is:");while(p){printf("%d ",p->data);p=p->next;}}printf("\n");return OK;}int LinkInsert_L(LinkList &L,int i,ElemType e) {LNode *p=L,*s;int j=0;while(p&&j<i-1){p=p->next;j++;}if(!p||j>i-1)return ERROR;s=(LinkList)malloc(sizeof(LNode));s->data=e;s->next=p->next;p->next=s;return OK;}int LinkDelete_L(LinkList &L,int i,ElemType &e) {LNode *p=L,*q;int j=0;while(p->next&&j<i-1){p=p->next;j++;}if(!(p->next)||j<i-1)return ERROR;q=p->next;p->next=q->next;e=q->data;free(q);return OK;}int main(){LinkList T;int a,n,i;ElemType x,e;printf("Please input the init size of the linklist:\n");scanf("%d",&n);printf("Please input the %d element of the linklist:\n",n);if(CreateLink_L(T,n)){printf("A Link List Has Created.\n");LoadLink_L(T);}while(1){printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n");scanf("%d",&a);switch(a){case 1:scanf("%d%d",&i,&x);if(!LinkInsert_L(T,i,x))printf("Insert Error!\n");elseprintf("The Element %d is Successfully Inserted!\n",x);break;case 2:scanf("%d",&i);if(!LinkDelete_L(T,i,e))printf("Delete Error!\n");elseprintf("The Element %d is Successfully Deleted!\n",e);break;case 3:LoadLink_L(T);break;case 0:return 1;}}}55555555555555555555555555555555555555555555555555555555555 5555555555555555555#include<stdio.h>#include<malloc.h>#define ERROR 0#define OK 1#define ElemType inttypedef struct LNode{int data;struct LNode *next;}LNode,*LinkList;int CreateLink_L(LinkList &L,int n){LinkList p,q;int i;ElemType e;L=(LinkList)malloc(sizeof(LNode));L->next=NULL;q=(LinkList)malloc(sizeof(LNode));q=L;for(i=0;i<n;i++){scanf("%d",&e);p=(LinkList)malloc(sizeof(LNode));p->data=e;p->next=q->next;q->next=p;q=q->next;}return OK;}int LoadLink_L(LinkList &L){LinkList p=L->next;if(!p)printf("The List is empty!");else{while(p){printf("%d ",p->data);p=p->next;}}printf("\n");return OK;}void MergeList_L(LinkList &La,LinkList &Lb,LinkList &Lc) {LinkList pa,pb,pc;pa=La->next;pb=Lb->next;Lc=pc=La;while(pa&&pb){if(pa->data<=pb->data){pc->next=pa;pc=pa;pa=pa->next;}else{pc->next=pb;pc=pb;pb=pb->next;}}pc->next=pa?pa:pb;free(Lb);}int main(){LinkList La,Lb,Lc;int n;scanf("%d",&n);CreateLink_L(La,n);printf("List A:");LoadLink_L(La);scanf("%d",&n);CreateLink_L(Lb,n);printf("List B:");LoadLink_L(Lb);MergeList_L(La,Lb,Lc);printf("List C:");LoadLink_L(Lc);return 0;}6666666666666666666666666666666666666666666666666666666666 66666666666666666666#include<stdio.h>#include<malloc.h>#define OK 1#define ERROR 0#define ElemType inttypedef struct LNode{int data;struct LNode *next;}LNode,*LinkList;int CreateLink_L(LinkList &L,int n){LinkList p,q;int i;ElemType e;L=(LinkList)malloc(sizeof(LNode));L->next=NULL;q=(LinkList)malloc(sizeof(LNode));q=L;for(i=0;i<n;i++){scanf("%d",&e);p=(LinkList)malloc(sizeof(LNode));p->data=e;p->next=q->next;q->next=p;q=q->next;}return OK;}int LoadLink_L(LinkList &L){LinkList p=L->next;if(!p)printf("The List is Empty!");elsewhile(p){printf("%d ",p->data);p=p->next;}printf("\n");return OK;}int inversion(LinkList &L){LinkList p=L->next,q;L->next=NULL;while(p){q=p->next;p->next=L->next;L->next=p;p=q;}return OK;}int main(){LinkList T;int n;scanf("%d",&n);CreateLink_L(T,n);printf("The List is:");LoadLink_L(T);inversion(T);printf("The turned List is:");LoadLink_L(T);return 0;}实验二实验二实验二实验二实验二实验二实验二实验二实验二实验二实验二实验二实验二#include<stdio.h>#include<malloc.h>#include<stdlib.h>#define OK 1#define ERROR 0#define STACK_INIT_SIZE 100 #define STACKINCREMENT 10typedef int SElemType; typedef int Status;struct SqStack{SElemType *base;SElemType *top;int stacksize;};Status InitStack(SqStack &S){S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));if(!S.base)return ERROR;S.top=S.base;S.stacksize=STACK_INIT_SIZE;return OK;}Status Push(SqStack &S,SElemType e){if(S.top-S.base>=S.stacksize){S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*s izeof(SElemType));if(S.base)return ERROR;S.top=S.base+S.stacksize;S.stacksize+=STACKINCREMENT;}*S.top++=e;return OK;}Status Pop(SqStack &S,SElemType &e) {if(S.top==S.base)return ERROR;e=*--S.top;return OK;}Status GetTop(SqStack S,SElemType &e) {if(S.top==S.base)return ERROR;e=*(S.top-1);return OK;}int StackLength(SqStack S){int i=0;while(S.top!=S.base){i++;S.top--;}return i;}Status StackTraverse(SqStack S){SElemType *p=(SElemType*)malloc(sizeof(SElemType));p=S.top;if(S.top==S.base)printf("The Stack is Empty!");else{printf("The Stack is:");p--;S.base--;while(p!=S.base){printf("% d",*p);p--;}}printf("\n");return OK;}int main(){int a;SqStack S;SElemType x,e;if(InitStack(S))printf("A Stack Has Created.\n");while(1){printf("1:Push\n2:Pop\n3:Get the Top\n4:Return the Length of the Stack\n5:Load the Stack\n0:Exit\nPlease choose:\n");scanf("%d",&a);switch(a){case 1:scanf("%d",&x);if(!Push(S,x))printf("Push Error!\n");elseprintf("The Element %d is Successfully Pushed!\n",x);break;case 2:if(!Pop(S,e))printf("Pop Error!\n");elseprintf("The Element %d is Successfully Poped!\n",e);break;case 3:if(!GetTop(S,e))printf("GetTop Error!\n");elseprintf("The Top Element is %d!\n",e);break;case 4:printf("The Length of the Stack is %d!\n",StackLength(S));break;case 5:StackTraverse(S);break;case 0:return 1;}}}2222222222222222222222222222222222222222222222222222222222 22222222222222222222#include<stdio.h>#include<malloc.h>#define ERROR 0#define OK 1#define STACK_INIT_SIZE 100#define STACKINCREMENT 10typedef int SElemType;typedef int Status;struct SqStack{SElemType *base;SElemType *top;int stacksize;};Status InitStack(SqStack &S){S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));if(!S.base)return ERROR;S.top=S.base;S.stacksize=STACK_INIT_SIZE;return OK;}Status Push(SqStack &S,SElemType e){if(S.top-S.base>=S.stacksize){S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*s izeof(SElemType));if(S.base)return ERROR;S.top=S.base+S.stacksize;S.stacksize+=STACKINCREMENT;}*S.top++=e;return OK;}Status Pop(SqStack &S,SElemType &e) {if(S.top==S.base)return ERROR;e=*--S.top;return OK;}Status StackEmpty(SqStack &S){if(S.top==S.base)return 0;elsereturn 1;}int main(){int N,e;SqStack S;InitStack(S);scanf("%d",&N);while(N){Push(S,N%8);N=N/8;}while(StackEmpty(S)){Pop(S,e);printf("%d",e);}return 0;}3333333333333333333333333333333333333333333333333333333333 33333333333333333333typedef char SElemType;#include<malloc.h>#include<stdio.h>#include<math.h>#include<process.h>#define OK 1#define ERROR 0#define TRUE 1#define FALSE 0typedef int Status;#define STACK_INIT_SIZE 10#define STACKINCREMENT 2struct SqStack{SElemType *base;SElemType *top;int stacksize;};Status InitStack(SqStack &S){S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));if(!S.base)return 0;S.top=S.base;S.stacksize=STACK_INIT_SIZE;return OK;}Status StackEmpty(SqStack S){if(S.top==S.base)return TRUE;elsereturn FALSE;}Status Push(SqStack &S,SElemType e){if(S.top-S.base>=S.stacksize){S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*s izeof(SElemType));if(!S.base)return 0;S.top=S.base+S.stacksize;S.stacksize+=STACKINCREMENT;}*S.top++=e;return OK;}Status Pop(SqStack &S,SElemType &e) {if(S.top==S.base)return ERROR;e=*--S.top;return OK;}void check(){SqStack s;SElemType ch[80],*p,e;if(InitStack(s)){gets(ch);p=ch;while(*p)switch(*p){case '(':case '[':Push(s,*p++);break;case ')':case ']':if(!StackEmpty(s)){Pop(s,e);if(*p==')'&&e!='('||*p==']'&&e!='[') {printf("isn't matched pairs\n");return ;}else{p++ ;break;}}else{printf("lack of left parenthesis\n");return ;}default: p++;}if(StackEmpty(s))printf("matching\n");elseprintf("lack of right parenthesis\n");}}int main(){check();return 1;}4444444444444444444444444444444444444444444444444444444444 44444444444444444444typedef char SElemType;#include<malloc.h>#include<stdio.h>#include<math.h>#include<process.h>#define OK 1#define ERROR 0#define TRUE 1#define FALSE 0typedef int Status;#define STACK_INIT_SIZE 10#define STACKINCREMENT 2struct SqStack{SElemType *base;SElemType *top;int stacksize;};FILE *fp;Status InitStack(SqStack &S){S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));if(!S.base)return 0;S.top=S.base;S.stacksize=STACK_INIT_SIZE;return OK;}Status StackEmpty(SqStack S) {if(S.top==S.base)return TRUE;elsereturn FALSE;}Status ClearStack(SqStack &S) {S.top=S.base;return OK;}Status DestroyStack(SqStack &S){free(S.base);S.base=NULL;S.top=NULL;S.stacksize=0;return OK;}Status Push(SqStack &S,SElemType e){if(S.top-S.base>=S.stacksize){S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*s izeof(SElemType));if(!S.base)return 0;S.top=S.base+S.stacksize;S.stacksize+=STACKINCREMENT;}*S.top++=e;return OK;}Status Pop(SqStack &S,SElemType &e){if(S.top==S.base)return ERROR;e=*--S.top;return OK;}Status StackTraverse(SqStack S,Status(*visit)(SElemType)) {while(S.top>S.base)visit(*S.base++);printf("\n");return OK;}Status visit(SElemType c){printf("%c",c);return OK;}void LineEdit(){SqStack s;char ch,c;int n,i;InitStack(s);scanf("%d",&n);ch=getchar();for(i=1;i<=n;i++){ch=getchar();while(ch!='\n'){switch(ch){case '#': Pop(s,c);break;case '@': ClearStack(s);break;default:Push(s,ch);}ch=getchar();}StackTraverse(s,visit);ClearStack(s);}DestroyStack(s);}int main(){LineEdit();return 1;} 55555555555555555555555555555555555555555555555555555555555 5555555555555555555#include<stdio.h>#include<malloc.h>#define OK 1#define ERROR 0#define STACK_INIT_SIZE 100#define STACKINCREMENT 10。
华农数据结构上机实验答案

华农数据结构上机实验答案数据结构上机答案1.1顺序线性表的基本操作#include<stdio.h>#include<malloc.h>#define OK 1#define ERROR 0#define LIST_INIT_SIZE 100#define LISTINCREMENT 10#define ElemType inttypedef struct{int *elem,length,listsize;}SqList;int InitList_Sq(SqList &L){L.elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));L.length=0;L.listsize=LIST_INIT_SIZE;return OK;}int Load_Sq(SqList &L){int i;if(L.length==0)printf("The List is empty!");else{printf("The List is:");for(i=0;i<L.length;i++)printf("% d",L.elem[i]);}printf("\n");return OK;}int ListInsert_Sq(SqList &L,int i,int e){if(i<1||i>L.length+1)return ERROR;ElemType *newbase,*q,*p;if(L.length>=L.listsize){newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*size of(ElemType));L.elem=newbase;L.listsize+=LISTINCREMENT;}q=&(L.elem[i-1]);for(p=&(L.elem[L.length-1]);p>=q;--p)*(p+1)=*p;*q=e;++L.length;return OK;}int ListDelete_Sq(SqList &L,int i,int &e){ElemType *q,*p;if(i<1||i>L.length)return ERROR;p=&(L.elem[i-1]);e=*p;q=L.elem+L.length-1;for(++p;p<=q;p++)*(p-1)=*p;L.length--;return OK;}int main(){SqList T;int a,i;ElemType e,x;if(InitList_Sq(T)){printf("A Sequence List Has Created.\n");}while(1){printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n");scanf("%d",&a);switch(a){case 1: scanf("%d%d",&i,&x);if(!ListInsert_Sq(T,i,x))printf("Insert Error!\n");elseprintf("The Element %d is Successfully Inserted!\n",x);break;case 2: scanf("%d",&i);if(!ListDelete_Sq(T,i,e))printf("Delete Error!\n");elseprintf("The Element %d is Successfully Deleted!\n",e);break;case 3: Load_Sq(T);break;case 0: return 1;}}}1.2合并顺序表#include<stdio.h>#include<malloc.h>#define OK 1#define ERROR 0#define LIST_INIT_SIZE 100#define LISTINCREMENT 10#define ElemType inttypedef struct{int *elem,length,listsize;}SqList;int InitList_Sq(SqList &L){L.elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));L.length=0;L.listsize=LIST_INIT_SIZE;return OK;}int Load_Sq(SqList &L){int i;for(i=0;i<L.length;i++)printf("%d ",L.elem[i]);printf("\n");return OK;}int ListLength(SqList L){return L.length;}int GetElem(SqList L,int i,ElemType &e){e=L.elem[i-1];return OK;}int ListInsert_Sq(SqList &L,int i,int e){if(i<1||i>L.length+1)return ERROR;ElemType *p,*q,*newbase;if(L.listsize<=L.length){newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*size of(ElemType));L.elem=newbase;L.listsize+=LISTINCREMENT;}q=&(L.elem[i-1]);for(p=&(L.elem[L.length-1]);p>=q;p--)*(p+1)=*p;*q=e;L.length++;return OK;}void MergeList(SqList La,SqList Lb,SqList &Lc){int i,j,k,La_len,Lb_len,ai,bj;i=j=1;k=0;InitList_Sq(Lc);La_len=ListLength(La);Lb_len=ListLength(Lb);while((i<=La_len)&&(j<=Lb_len)){GetElem(La,i,ai);GetElem(Lb,j,bj);if(ai<=bj){ListInsert_Sq(Lc,++k,ai);i++;}else{ListInsert_Sq(Lc,++k,bj);j++;}}while(i<=La_len){GetElem(La,i++,ai);ListInsert_Sq(Lc,++k,ai);}while(j<=Lb_len){GetElem(Lb,j++,bj);ListInsert_Sq(Lc,++k,bj);}Load_Sq(Lc);}int main(){int an,bn,i,e;SqList La,Lb,Lc;InitList_Sq(La);scanf("%d",&an);for(i=1;i<=an;i++){scanf("%d",&e);ListInsert_Sq(La,i,e);}printf("List A:");Load_Sq(La);InitList_Sq(Lb);scanf("%d",&bn);for(i=1;i<=an;i++){scanf("%d",&e);ListInsert_Sq(Lb,i,e);}printf("List B:");Load_Sq(Lb);printf("List C:");MergeList(La,Lb,Lc);return 0;}1.3顺序表逆置#include<stdio.h>#include<malloc.h>#define OK 1#define ERROR 0#define LIST_INIT_SIZE 100#define LISTINCREMENT 10#define ElemType inttypedef struct{int *elem,length,listsize;}SqList;int InitList_Sq(SqList &L){L.elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));if(!L.elem){printf("NO1");return ERROR;}L.length=0;L.listsize=LIST_INIT_SIZE;return OK;}int Load_Sq(SqList &L){int i;if(!L.length){printf("This List is empty!\n");return ERROR;}else{for(i=0;i<L.length;i++)printf("%d ",L.elem[i]);}printf("\n");return OK;}int ListInsert_Sq(SqList &L,int i,int e){ElemType *newbase,*p,*q;if(L.length>=L.listsize){newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*size of(ElemType));if(!newbase){printf("NO2");return ERROR;}L.elem=newbase;L.listsize+=LISTINCREMENT;}q=&(L.elem[i-1]);for(p=&(L.elem[L.length-1]);p>=q;p--)*(p+1)=*p;*q=e;L.length++;return OK;}int swap(SqList &L,int n){int i,j,temp;for(i=0,j=n-1;j>i;i++,j--){temp=L.elem[i];L.elem[i]=L.elem[j];L.elem[j]=temp;}return OK;}int main(){SqList T;int n,i;ElemType x;scanf("%d",&n);InitList_Sq(T);for(i=1;i<n+1;i++){scanf("%d",&x);ListInsert_Sq(T,i,x);}printf("The List is:");Load_Sq(T);swap(T,n);printf("The turned List is:");Load_Sq(T);return 0;}1.4链式线性表的基本操作#include<stdio.h>#include<malloc.h>#define ERROR 0#define OK 1#define ElemType inttypedef struct LNode{int data;struct LNode *next;}LNode,*LinkList;int CreateLink_L(LinkList &L,int n){LinkList p,q;int i;ElemType e;L=(LinkList)malloc(sizeof(LNode));L->next=NULL;q=(LinkList)malloc(sizeof(LNode));q=L;for(i=0;i<n;i++){scanf("%d",&e);p=(LinkList)malloc(sizeof(LNode));p->data=e;p->next=q->next;q->next=p;q=q->next;}return OK;}int LoadLink_L(LinkList &L){LinkList p=L->next;if(!p)printf("The List is empty!");else{printf("The LinkList is:");while(p){printf("%d ",p->data);p=p->next;}}printf("\n");return OK;}int LinkInsert_L(LinkList &L,int i,ElemType e) {LNode *p=L,*s;int j=0;while(p&&j<i-1){p=p->next;j++;}if(!p||j>i-1)return ERROR;s=(LinkList)malloc(sizeof(LNode));s->data=e;s->next=p->next;p->next=s;return OK;}int LinkDelete_L(LinkList &L,int i,ElemType &e){LNode *p=L,*q;int j=0;while(p->next&&j<i-1){p=p->next;j++;}if(!(p->next)||j<i-1)return ERROR;q=p->next;p->next=q->next;e=q->data;free(q);return OK;}int main(){LinkList T;int a,n,i;ElemType x,e;printf("Please input the init size of the linklist:\n");scanf("%d",&n);printf("Please input the %d element of the linklist:\n",n);if(CreateLink_L(T,n)){printf("A Link List Has Created.\n");LoadLink_L(T);}while(1){printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n");scanf("%d",&a);switch(a){case 1:scanf("%d%d",&i,&x);if(!LinkInsert_L(T,i,x))printf("Insert Error!\n");elseprintf("The Element %d is Successfully Inserted!\n",x);break;case 2:scanf("%d",&i);if(!LinkDelete_L(T,i,e))printf("Delete Error!\n");elseprintf("The Element %d is Successfully Deleted!\n",e);break;case 3:LoadLink_L(T);break;case 0:return 1;}}}1.5合并链表#include<stdio.h>#include<malloc.h>#define ERROR 0#define OK 1#define ElemType inttypedef struct LNode{int data;struct LNode *next;}LNode,*LinkList;int CreateLink_L(LinkList &L,int n){LinkList p,q;int i;ElemType e;L=(LinkList)malloc(sizeof(LNode));L->next=NULL;q=(LinkList)malloc(sizeof(LNode));q=L;for(i=0;i<n;i++){scanf("%d",&e);p=(LinkList)malloc(sizeof(LNode));p->data=e;p->next=q->next;q->next=p;q=q->next;}return OK;}int LoadLink_L(LinkList &L){LinkList p=L->next;if(!p)printf("The List is empty!");else{while(p){printf("%d ",p->data);p=p->next;}}printf("\n");return OK;}void MergeList_L(LinkList &La,LinkList &Lb,LinkList &Lc) {LinkList pa,pb,pc;pa=La->next;pb=Lb->next;Lc=pc=La;while(pa&&pb){if(pa->data<=pb->data){pc->next=pa;pc=pa;pa=pa->next;}else{pc->next=pb;pc=pb;pb=pb->next;}}pc->next=pa?pa:pb;free(Lb);}int main(){LinkList La,Lb,Lc;int n;scanf("%d",&n);CreateLink_L(La,n);printf("List A:");LoadLink_L(La);scanf("%d",&n);CreateLink_L(Lb,n);printf("List B:");LoadLink_L(Lb);MergeList_L(La,Lb,Lc);printf("List C:");LoadLink_L(Lc);return 0;}1.6线性链表逆置#include<stdio.h>#include<malloc.h>#define OK 1#define ERROR 0#define ElemType inttypedef struct LNode{int data;struct LNode *next;}LNode,*LinkList;int CreateLink_L(LinkList &L,int n){LinkList p,q;int i;ElemType e;L=(LinkList)malloc(sizeof(LNode));L->next=NULL;q=(LinkList)malloc(sizeof(LNode));q=L;for(i=0;i<n;i++){scanf("%d",&e);p=(LinkList)malloc(sizeof(LNode));p->data=e;p->next=q->next;q->next=p;q=q->next;}return OK;}int LoadLink_L(LinkList &L){LinkList p=L->next;if(!p)printf("The List is Empty!");elsewhile(p){printf("%d ",p->data);p=p->next;}printf("\n");return OK;}int inversion(LinkList &L){LinkList p=L->next,q;L->next=NULL;while(p){q=p->next;p->next=L->next;L->next=p;p=q;}return OK;}int main(){LinkList T;int n;scanf("%d",&n);CreateLink_L(T,n);printf("The List is:");LoadLink_L(T);inversion(T);printf("The turned List is:");LoadLink_L(T);return 0;}2.1顺序栈的基本操作#include<stdio.h>#include<malloc.h>#include<stdlib.h>#define OK 1#define ERROR 0#define STACK_INIT_SIZE 100#define STACKINCREMENT 10typedef int SElemType;typedef int Status;struct SqStack{SElemType *base;SElemType *top;int stacksize;};Status InitStack(SqStack &S){S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));if(!S.base)return ERROR;S.top=S.base;S.stacksize=STACK_INIT_SIZE;return OK;}Status Push(SqStack &S,SElemType e){if(S.top-S.base>=S.stacksize){S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*si zeof(SElemType));if(S.base)return ERROR;S.top=S.base+S.stacksize;S.stacksize+=STACKINCREMENT;}*S.top++=e;return OK;}Status Pop(SqStack &S,SElemType &e){if(S.top==S.base)return ERROR;e=*--S.top;return OK;}Status GetTop(SqStack S,SElemType &e){if(S.top==S.base)return ERROR;e=*(S.top-1);return OK;}int StackLength(SqStack S){int i=0;while(S.top!=S.base){i++;S.top--;}return i;}Status StackTraverse(SqStack S){SElemType *p=(SElemType*)malloc(sizeof(SElemType));p=S.top;if(S.top==S.base)printf("The Stack is Empty!");else{printf("The Stack is:");p--;S.base--;while(p!=S.base){printf("% d",*p);p--;}}printf("\n");return OK;}int main(){int a;SqStack S;SElemType x,e;if(InitStack(S))printf("A Stack Has Created.\n");while(1){printf("1:Push\n2:Pop\n3:Get the Top\n4:Return the Length of the Stack\n5:Load the Stack\n0:Exit\nPlease choose:\n");scanf("%d",&a);switch(a){case 1:scanf("%d",&x);if(!Push(S,x))printf("Push Error!\n");elseprintf("The Element %d is Successfully Pushed!\n",x);break;case 2:if(!Pop(S,e))printf("Pop Error!\n");elseprintf("The Element %d is Successfully Poped!\n",e);break;case 3:if(!GetTop(S,e))printf("GetTop Error!\n");elseprintf("The Top Element is %d!\n",e);break;case 4:printf("The Length of the Stack is %d!\n",StackLength(S));break;case 5:StackTraverse(S);break;case 0:return 1;}}}2.2循环队列的基本操作#include<stdio.h>#include<malloc.h>#define OK 1#define ERROR 0typedef int Status;typedef int QElemType;#define MAXQSIZE 100typedef struct{QElemType *base;int front;int rear;}SqQueue;Status InitQueue(SqQueue &Q){Q.base=(QElemType*)malloc(MAXQSIZE*sizeof(QElemType));if(!Q.base)return ERROR;Q.front=Q.rear=0;return OK;}Status EnQueue(SqQueue &Q,QElemType e){if((Q.rear+1)%MAXQSIZE==Q.front)return ERROR;Q.base[Q.rear]=e;Q.rear=(Q.rear+1)%MAXQSIZE;return OK;}Status DeQueue(SqQueue &Q,QElemType &e){if(Q.front==Q.rear)return ERROR;e=Q.base[Q.front];Q.front=(Q.front+1)%MAXQSIZE;return OK;}Status GetHead(SqQueue Q,QElemType &e){if(Q.front==Q.rear)return ERROR;e=Q.base[Q.front];return OK;}int QueueLength(SqQueue Q){return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE; }Status QueueTraverse(SqQueue Q){int i;i=Q.front;if(Q.front==Q.rear)printf("The Queue is Empty!");else{printf("The Queue is:");while(i!=Q.rear){printf("% d",Q.base[i]);i=i+1;}}printf("\n");return OK;}int main(){int a;SqQueue S;QElemType x,e;if(InitQueue(S))printf("A Queue Has Created.\n");while(1){printf("1:Enter \n2:Delete \n3:Get the Front \n4:Return the Length of the Queue\n5:Load the Queue\n0:Exit\nPlease choose:\n");scanf("%d",&a);switch(a){case 1: scanf("%d",&x);if(!EnQueue(S,x))printf("Enter Error!\n");elseprintf("The Element %d is Successfully Entered!\n",x);break;case 2: if(!DeQueue(S,e))printf("Delete Error!\n");elseprintf("The Element %d is Successfully Deleted!\n",e);break;case 3: if(!GetHead(S,e))printf("Get Head Error!\n");elseprintf("The Head of the Queue is %d!\n",e);break;case 4: printf("The Length of the Queue is %d!\n",QueueLength(S));break;case 5: QueueTraverse(S);break;case 0: return 1;}}}2.3栈的应用——进制转换#include<stdio.h>#include<malloc.h>#define ERROR 0#define OK 1#define STACK_INIT_SIZE 100#define STACKINCREMENT 10typedef int SElemType;typedef int Status;struct SqStack{SElemType *base;SElemType *top;int stacksize;};Status InitStack(SqStack &S){S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));if(!S.base)return ERROR;S.top=S.base;S.stacksize=STACK_INIT_SIZE;return OK;}Status Push(SqStack &S,SElemType e){if(S.top-S.base>=S.stacksize){S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*si zeof(SElemType));if(S.base)return ERROR;S.top=S.base+S.stacksize;S.stacksize+=STACKINCREMENT;}*S.top++=e;return OK;}Status Pop(SqStack &S,SElemType &e){if(S.top==S.base)return ERROR;e=*--S.top;return OK;}Status StackEmpty(SqStack &S){if(S.top==S.base)return 0;elsereturn 1;}int main(){int N,e;SqStack S;InitStack(S);scanf("%d",&N);while(N){Push(S,N%8);N=N/8;}while(StackEmpty(S)){Pop(S,e);printf("%d",e);}return 0;}2.4括号匹配检验typedef char SElemType;#include<malloc.h>#include<stdio.h>#include<math.h>#include<process.h>#define OK 1#define ERROR 0#define TRUE 1#define FALSE 0typedef int Status;#define STACK_INIT_SIZE 10#define STACKINCREMENT 2struct SqStack{SElemType *base;SElemType *top;int stacksize;};Status InitStack(SqStack &S){S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));if(!S.base)return 0;S.top=S.base;S.stacksize=STACK_INIT_SIZE;return OK;}Status StackEmpty(SqStack S){if(S.top==S.base)return TRUE;elsereturn FALSE;}Status Push(SqStack &S,SElemType e){if(S.top-S.base>=S.stacksize){S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*si zeof(SElemType));if(!S.base)return 0;S.top=S.base+S.stacksize;S.stacksize+=STACKINCREMENT;}*S.top++=e;return OK;}Status Pop(SqStack &S,SElemType &e){if(S.top==S.base)return ERROR;e=*--S.top;return OK;}void check(){SqStack s;SElemType ch[80],*p,e;if(InitStack(s)){gets(ch);p=ch;while(*p)switch(*p){case '(':case '[':Push(s,*p++);break;case ')':case ']':if(!StackEmpty(s)){Pop(s,e);if(*p==')'&&e!='('||*p==']'&&e!='[') {printf("isn't matched pairs\n");return ;}else{p++ ;break;}}else{printf("lack of left parenthesis\n");return ;}default: p++;}if(StackEmpty(s))printf("matching\n");elseprintf("lack of right parenthesis\n");}}int main(){check();return 1;}2.5行编辑程序typedef char SElemType;#include<malloc.h>#include<stdio.h>#include<math.h>#include<process.h>#define OK 1#define ERROR 0#define TRUE 1#define FALSE 0typedef int Status;#define STACK_INIT_SIZE 10#define STACKINCREMENT 2struct SqStack{SElemType *base;SElemType *top;int stacksize;};FILE *fp;Status InitStack(SqStack &S){S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));if(!S.base)return 0;S.top=S.base;S.stacksize=STACK_INIT_SIZE;return OK;}Status StackEmpty(SqStack S){if(S.top==S.base)return TRUE;elsereturn FALSE;}Status ClearStack(SqStack &S){S.top=S.base;return OK;}Status DestroyStack(SqStack &S){free(S.base);S.base=NULL;S.top=NULL;S.stacksize=0;return OK;}Status Push(SqStack &S,SElemType e){if(S.top-S.base>=S.stacksize){S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*si zeof(SElemType));if(!S.base)return 0;S.top=S.base+S.stacksize;S.stacksize+=STACKINCREMENT;}*S.top++=e;return OK;}Status Pop(SqStack &S,SElemType &e){if(S.top==S.base)return ERROR;e=*--S.top;return OK;}Status StackTraverse(SqStack S,Status(*visit)(SElemType)) {while(S.top>S.base)visit(*S.base++);printf("\n");return OK;}Status visit(SElemType c){printf("%c",c);return OK;}void LineEdit(){SqStack s;char ch,c;int n,i;InitStack(s);scanf("%d",&n);ch=getchar();for(i=1;i<=n;i++){ch=getchar();while(ch!='\n'){switch(ch){case '#': Pop(s,c);break;case '@': ClearStack(s);break;default:Push(s,ch);}ch=getchar();}StackTraverse(s,visit);ClearStack(s);}DestroyStack(s);}int main(){LineEdit();return 1;}2.6表达式求值#include<stdio.h>#include<malloc.h>#define OK 1#define ERROR 0#define STACK_INIT_SIZE 100#define STACKINCREMENT 10typedef int Status;struct SqStack_T{char *base;char *top;int stacksize;};struct SqStack_N{int *base;int *top;int stacksize;};Status InitStack_T(SqStack_T &S){S.base=(char*)malloc(STACK_INIT_SIZE*sizeof(char));if(!S.base)return ERROR;S.top=S.base;S.stacksize=STACK_INIT_SIZE;return OK;}Status InitStack_N(SqStack_N &S){S.base=(int*)malloc(STACK_INIT_SIZE*sizeof(int));if(!S.base)return ERROR;S.top=S.base;S.stacksize=STACK_INIT_SIZE;return OK;}int Push_T(SqStack_T &S,char e){if(S.top-S.base>=S.stacksize){S.base=(char*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof( char));if(!S.base)return ERROR;S.top=S.base+S.stacksize;S.stacksize+=STACKINCREMENT;}*S.top++=e;return OK;}int Push_N(SqStack_N &S,int e){if(S.top-S.base>=S.stacksize){S.base=(int*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(i nt));if(!S.base)return ERROR;S.top=S.base+S.stacksize;S.stacksize+=STACKINCREMENT;}*S.top++=e;return OK;}int Pop_T(SqStack_T &S,char &e){if(S.top==S.base)return ERROR;e=*--S.top;return OK;}int Pop_N(SqStack_N &S,int &e){if(S.top==S.base)return ERROR;e=*--S.top;return OK;}char GetTop_T(SqStack_T S){char e;if(S.top==S.base)return ERROR;e=*(S.top-1);return e;}int GetTop_N(SqStack_N S){int e;if(S.top==S.base)return ERROR;e=*(S.top-1);return e;}char Precede(char theta1,char theta2) {int a,b;switch(theta1){case '+': a=2; break;case '-': a=2; break;case '*': a=4; break;case '/': a=4; break;case '(': a=0; break;case ')': a=6; break;case '=': a=-1; break;}switch(theta2){case '+': b=1; break;case '-': b=1; break;case '*': b=3; break;case '/': b=3; break;case '(': b=6; break;case ')': b=0; break;case '=': b=-1; break;}if(a<b)return '<';elseif(a==b)return '=';elsereturn '>';}char precede(char e,char c){if(c=='+'||c=='-'){if(e=='+'||e=='-'||e==')'||e=='=') return '>';elsereturn '<';}if(c=='*'||'/'){if(e=='(')return '<';elsereturn '>';}if(c=='('){if(e==')')return '=';elsereturn '<';}if(c==')')return '>';if(c=='='){if(e=='=')return '=';elsereturn '<';}}int In(char c){if(c>='0'&&c<='9')return 1;elsereturn 0;}int Operate(int a,char theta,int b){int s;switch(theta){case '+': s=a+b; break;case '-': s=a-b; break;case '*': s=a*b; break;case '/':if(b!=0)s=a/b;elseprintf("Input error");break;}return s;}int main(){int k=0,m,y,a,b;SqStack_T OPTR;SqStack_N OPND;char c,theta;InitStack_T(OPTR); Push_T(OPTR,'=');InitStack_N(OPND); c=getchar();while(c!='='||GetTop_T(OPTR)!='='){if(In(c)){m=c-'0';if(k==1){Pop_N(OPND,y);y=m+y*10;Push_N(OPND,y);k=1;c=getchar();}else{y=m;Push_N(OPND,y);c=getchar();k=1;}}else{k=0;switch(Precede(GetTop_T(OPTR),c)){case '<': Push_T(OPTR,c); c=getchar(); break;case '=': Pop_T(OPTR,c); c=getchar(); break;case '>':Pop_T(OPTR,theta);Pop_N(OPND,b);Pop_N(OPND,a);Push_N(OPND,Operate(a,theta,b));break;}}}printf("%d",GetTop_N(OPND));return 0;}2.7队列的应用——银行客户平均等待时间#include<malloc.h>#include<stdio.h>#define OK 1#define ERROR 0typedef int Status;typedef int QElemType;#define MAXQSIZE 100typedef struct{QElemType *base;int front;int rear;}SqQueue;Status InitQueue(SqQueue &Q){Q.base=(QElemType*)malloc(MAXQSIZE*sizeof(QElemType));if(!Q.base)return ERROR;Q.front=Q.rear=0;return OK;}Status EnQueue(SqQueue &Q,QElemType e){if((Q.rear+1)%MAXQSIZE==Q.front)return ERROR;Q.base[Q.rear]=e;Q.rear=(Q.rear+1)%MAXQSIZE;return OK;}Status DeQueue(SqQueue &Q,QElemType &e){if(Q.front==Q.rear)return ERROR;e=Q.base[Q.front];Q.front=(Q.front+1)%MAXQSIZE;return OK;}Status GetHead(SqQueue Q,QElemType &e){if(Q.rear==Q.front)return ERROR;e=Q.base[Q.front];return OK;}int QueueLength(SqQueue Q){return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE; }Status QueueTraverse(SqQueue Q){int i;i=Q.front;if(Q.rear==Q.front)printf("The Queue is Empty!");else{printf("The Queu is:");while(i!=Q.rear){printf("%d",Q.base[i]);i=(i+1)%MAXQSIZE;}}printf("\n");return OK;}int main(){int i,a;SqQueue S;int p,q,e,r;float t,s=0;InitQueue(S);scanf("%d",&a);getchar();for(i=1;i<=a*2;i++){scanf("%d",&e);getchar();EnQueue(S,e);}p=S.base[S.front];while(S.rear>S.front){q=p+S.base[S.front+1];DeQueue(S,e);DeQueue(S,e);if(S.front==S.rear)break;r=q-S.base[S.front];if(r<0){r=0;p=S.base[S.front];continue;}s=s+r;p=q;}t=s/a;printf("%.2f\n",t);return OK;}3.1计算next值#include<stdio.h>#include<stdlib.h>#include<iostream.h>#define MAXSTRLEN 255typedef unsigned char SString[MAXSTRLEN+1];void get_next(SString T,int next[]){int i=1,j=0;next[1]=0;while(i<T[0]){if(j==0||T[i]==T[j]){i++;j++;next[i]=j;}elsej=next[j];}}。
数据结构上机答案(c语言版)

数据结构上机答案(c语言版)实习一:1、编写一个读入一个字符串,把它存入一个链表,并按相反的次序打印的程序。
2、设有一个单位的人员工资有如下信息:name、department、base pay、allowance、total。
现从键盘输入一组人员工资数据并将它们存储到名为paydata的文件中;再从paydata取出工资数据并给每个人的base pay增加100元,增加后将工资数据显示于屏幕(每行1人)。
请编写能够完成上述工作的程序。
代码如下:1.#include#include#includevoid main(){char x;struct node //定义个结构node{char c;struct node *next;};struct node *head,*pb,*pf,*p,*s,*t; //定义指针printf("请输入字符串,按Enter结束!\n");for(int i=0;x!='\n';i++){pb=(struct node *)malloc(sizeof(struct node));//动态分配n字节的内存空间scanf("%c",&pb->c); //输入字符x=pb->c;if(i==0){ //输入的首个字符作为头结点pfhead=pb;pf=head;}else if(pb->c!='\n'){ //如果输入的是Enter,输入终止,否则把字符依次存入链表pf->next=pb; //把输入的字符pb存在pf后,pb后为空pb->next=NULL;pf=pb;//pb赋给pf,重复上述操作p=head;}}for(;p!=NULL;p=p->next)s=p; //把指向链表的最后一个字符的指针赋给sprintf("输出结果为:\n");printf("%c",s->c);//输出链表的最后一个字符for(p=head;s!=head;)//若s==head,该链表只有一个字符。
数据结构实验答案

# include
# define maxnum 20
typedef int DataType ;
typedef struct
{ DataType data[maxnum] ;
int length ;
}SeqList ;
int MergeQL(SeqList la , SeqList lb , SeqList *lc)
实验一 线性表的顺序存储实验
一,实验目的
1,掌握用Visual C++6.0上机调试顺序表的基本方法
2,掌握顺序表的基本操作,插入,删除,查找,以及有序顺序表的合并等算法的实现
二,实验内容
1,顺序表基本操作的实现
[问题描述] 当我们要在顺序表的第i个位置上插入一个元素时,必须先将顺序表中第i个元素之后的所有元素依次后移一个位置,以便腾空一个位置,再把新元素插入到该位置.若是欲删除第i个元素时,也必须把第i个元素之后的所有元素前移一个位置.
ListNode *s,*r; /*工作指针*/
r=head; /*尾指针初值也指向头结点*/
while((ch=getchar())!='\n')
{
s=(ListNode *)malloc(sizeof(ListNode));
s->data=ch;
r->next=s;
r=s;
}
(*L)->next=NULL;
}
int List_Length(ListNode *L )
{
int n=0;ListNode *p=L->next;
while(p!=NULL)
数据结构上机实验

目录第1章绪论——上机实验题1解析实验题1.1求素数实验题1.2求一个正整数的各位数字之和实验题1.3求一个字符串是否为回文第2章线性表——上机实验题2解析实验题2.1实现顺序表各种基本运算的算法/*文件名:algo2-1.cpp*/#include <stdio.h>#include <malloc.h>#define MaxSize 50typedef char ElemType;typedef struct{ElemType elem[MaxSize];int length;} SqList;void InitList(SqList *&L){L=(SqList *)malloc(sizeof(SqList));L->length=0;}void DestroyList(SqList *L){free(L);}int ListEmpty(SqList *L){return(L->length==0);}int ListLength(SqList *L){return(L->length);}void DispList(SqList *L){int i;if (ListEmpty(L)) return;for (i=0;i<L->length;i++)printf("%c",L->elem[i]);printf("\n");}int GetElem(SqList *L,int i,ElemType &e){if (i<1 || i>L->length)return 0;e=L->elem[i-1];return 1;}int LocateElem(SqList *L, ElemType e){int i=0;while (i<L->length && L->elem[i]!=e) i++;if (i>=L->length)return 0;elsereturn i+1;}int ListInsert(SqList *&L,int i,ElemType e){int j;if (i<1 || i>L->length+1)return 0;i--; /*将顺序表位序转化为elem下标*/for (j=L->length;j>i;j--) /*将elem[i]及后面元素后移一个位置*/L->elem[j]=L->elem[j-1];L->elem[i]=e;L->length++; /*顺序表长度增1*/return 1;}int ListDelete(SqList *&L,int i,ElemType &e){int j;if (i<1 || i>L->length)return 0;i--; /*将顺序表位序转化为elem下标*/e=L->elem[i];for (j=i;j<L->length-1;j++)L->elem[j]=L->elem[j+1];L->length--;return 1;}实验题2.2实现单链表各种基本运算的算法*文件名:algo2-2.cpp*/#include <stdio.h>#include <malloc.h>typedef char ElemType;typedef struct LNode /*定义单链表结点类型*/{ElemType data;struct LNode *next;} LinkList;void InitList(LinkList *&L){L=(LinkList *)malloc(sizeof(LinkList)); /*创建头结点*/L->next=NULL;}void DestroyList(LinkList *&L){LinkList *p=L,*q=p->next;while (q!=NULL){free(p);p=q;q=p->next;}free(p);}int ListEmpty(LinkList *L){return(L->next==NULL);}int ListLength(LinkList *L){LinkList *p=L;int i=0;while (p->next!=NULL){i++;p=p->next;}return(i);}void DispList(LinkList *L){LinkList *p=L->next;while (p!=NULL){printf("%c",p->data);p=p->next;}printf("\n");}int GetElem(LinkList *L,int i,ElemType &e) {int j=0;LinkList *p=L;while (j<i && p!=NULL){j++;p=p->next;}if (p==NULL)return 0;else{e=p->data;return 1;}}int LocateElem(LinkList *L,ElemType e){LinkList *p=L->next;int n=1;while (p!=NULL && p->data!=e){p=p->next;n++;}if (p==NULL)return(0);elsereturn(n);}int ListInsert(LinkList *&L,int i,ElemType e)int j=0;LinkList *p=L,*s;while (j<i-1 && p!=NULL){j++;p=p->next;}if (p==NULL) /*未找到第i-1个结点*/return 0;else /*找到第i-1个结点*p*/{s=(LinkList *)malloc(sizeof(LinkList)); /*创建新结点*s*/s->data=e;s->next=p->next; /*将*s插p->next=s;return 1;}}int ListDelete(LinkList *&L,int i,ElemType &e){int j=0;LinkList *p=L,*q;while (j<i-1 && p!=NULL){j++;p=p->next;}if (p==NULL) /*未找到第i-1个结点*/return 0;else /*找到第i-1个结点*p*/{q=p->next; /*q指向要删除的结点*/p->next=q->next; /*从单链表中删除*q结点*/free(q); /*释放*q结点*/return 1;}}第3章栈和队列——上机实验题3解析实验题3.1实现顺序栈各种基本运算的算法*文件名:algo3-1.cpp*/#include <stdio.h>#include <malloc.h>#define MaxSize 100typedef char ElemType;typedef struct{ElemType elem[MaxSize];int top; /*栈指针*/} SqStack;void InitStack(SqStack *&s){s=(SqStack *)malloc(sizeof(SqStack));s->top=-1;}void ClearStack(SqStack *&s){free(s);}int StackLength(SqStack *s){return(s->top+1);}int StackEmpty(SqStack *s){return(s->top==-1);}int Push(SqStack *&s,ElemType e){if (s->top==MaxSize-1)return 0;s->top++;s->elem[s->top]=e;return 1;}int Pop(SqStack *&s,ElemType &e){if (s->top==-1)return 0;e=s->elem[s->top];s->top--;return 1;int GetTop(SqStack *s,ElemType &e){if (s->top==-1)return 0;e=s->elem[s->top];return 1;}void DispStack(SqStack *s){int i;for (i=s->top;i>=0;i--)printf("%c ",s->elem[i]);printf("\n");}实验题3.2实现链栈各种基本运算的算法/*文件名:algo3-2.cpp*/#include <stdio.h>#include <malloc.h>typedef char ElemType;typedef struct linknode{ElemType data; /*数据域*/struct linknode *next; /*指针域*/} LiStack;void InitStack(LiStack *&s){s=(LiStack *)malloc(sizeof(LiStack));s->next=NULL;}void ClearStack(LiStack *&s){LiStack *p=s->next;while (p!=NULL){free(s);s=p;p=p->next;}}int StackLength(LiStack *s){int i=0;LiStack *p;p=s->next;while (p!=NULL){i++;p=p->next;}return(i);}int StackEmpty(LiStack *s){return(s->next==NULL);}void Push(LiStack *&s,ElemType e){LiStack *p;p=(LiStack *)malloc(sizeof(LiStack));p->data=e;p->next=s->next; /*插入*p结点作为第一个数据结点*/s->next=p;}int Pop(LiStack *&s,ElemType &e){LiStack *p;if (s->next==NULL) /*栈空的情况*/return 0;p=s->next; /*p指向第一个数据结点*/e=p->data;s->next=p->next;free(p);return 1;}int GetTop(LiStack *s,ElemType &e){if (s->next==NULL) /*栈空的情况*/return 0;e=s->next->data;return 1;}void DispStack(LiStack *s){LiStack *p=s->next;while (p!=NULL){printf("%c ",p->data);p=p->next;}printf("\n");}实验题3.3实现顺序队列各种基本运算的算法/*文件名:algo3-3.cpp*/#include <stdio.h>#include <malloc.h>#define MaxSize 5typedef char ElemType;typedef struct{ElemType elem[MaxSize];int front,rear; /*队首和队尾指针*/} SqQueue;void InitQueue(SqQueue *&q){q=(SqQueue *)malloc (sizeof(SqQueue));q->front=q->rear=0;}void ClearQueue(SqQueue *&q){free(q);}int QueueEmpty(SqQueue *q){return(q->front==q->rear);}int QueueLength(SqQueue *q){return (q->rear-q->front+MaxSize)%MaxSize; }int enQueue(SqQueue *&q,ElemType e){if ((q->rear+1)%MaxSize==q->front) /*队满*/return 0;q->rear=(q->rear+1)%MaxSize;q->elem[q->rear]=e;return 1;}int deQueue(SqQueue *&q,ElemType &e){if (q->front==q->rear) /*队空*/return 0;q->front=(q->front+1)%MaxSize;e=q->elem[q->front];return 1;}实验题3.4实现链队各种基本运算的算法/*文件名:algo3-4.cpp*/#include <stdio.h>#include <malloc.h>typedef char ElemType;typedef struct qnode{ElemType data;struct qnode *next;} QNode;typedef struct{QNode *front;QNode *rear;} LiQueue;void InitQueue(LiQueue *&q){q=(LiQueue *)malloc(sizeof(LiQueue));q->front=q->rear=NULL;}void ClearQueue(LiQueue *&q){QNode *p=q->front,*r;if (p!=NULL) /*释放数据结点占用空间*/{r=p->next;while (r!=NULL){free(p);p=r;r=p->next;}}free(q); /*释放头结点占用空间*/ }int QueueLength(LiQueue *q){int n=0;QNode *p=q->front;while (p!=NULL){n++;p=p->next;}return(n);}int QueueEmpty(LiQueue *q){if (q->rear==NULL)return 1;elsereturn 0;}void enQueue(LiQueue *&q,ElemType e){QNode *s;s=(QNode *)malloc(sizeof(QNode));s->data=e;s->next=NULL;if (q->rear==NULL) /*若链队为空,则新结点是队首结点又是队尾结点*/q->front=q->rear=s;else{q->rear->next=s; /*将*s结点链到队尾,rear指向它*/q->rear=s;}}int deQueue(LiQueue *&q,ElemType &e){QNode *t;if (q->rear==NULL) /*队列为空*/return 0;if (q->front==q->rear) /*队列中只有一个结点时*/{t=q->front;q->front=q->rear=NULL;}else /*队列中有多个结点时*/{t=q->front;q->front=q->front->next;}e=t->data;free(t);return 1;}第4章串——上机实验题4解析实验题4.1实现顺序串各种基本运算的算法/*文件名:algo4-1.cpp*/#include <stdio.h>#define MaxSize 100 /*最多的字符个数*/typedef struct{ char ch[MaxSize]; /*定义可容纳MaxSize个字符的空间*/ int len; /*标记当前实际串长*/} SqString;void StrAssign(SqString &str,char cstr[]) /*str为引用型参数*/ {int i;for (i=0;cstr[i]!='\0';i++)str.ch[i]=cstr[i];str.len=i;}void StrCopy(SqString &s,SqString t) /*s为引用型参数*/ {int i;for (i=0;i<t.len;i++)s.ch[i]=t.ch[i];s.len=t.len;}int StrEqual(SqString s,SqString t){int same=1,i;if (s.len!=t.len) /*长度不相等时返回0*/same=0;else{for (i=0;i<s.len;i++)if (s.ch[i]!=t.ch[i]) /*有一个对应字符不相同时返回0*/same=0;}return same;}int StrLength(SqString s){return s.len;}SqString Concat(SqString s,SqString t){SqString str;int i;str.len=s.len+t.len;for (i=0;i<s.len;i++) /*将s.ch[0]~s.ch[s.len-1]复制到str*/ str.ch[i]=s.ch[i];for (i=0;i<t.len;i++) /*将t.ch[0]~t.ch[t.len-1]复制到str*/ str.ch[s.len+i]=t.ch[i];return str;}SqString SubStr(SqString s,int i,int j){SqString str;int k;str.len=0;if (i<=0 || i>s.len || j<0 || i+j-1>s.len){printf("参数不正确\n");return str; /*参数不正确时返回空串*/}for (k=i-1;k<i+j-1;k++) /*将s.ch[i]~s.ch[i+j]复制到str*/str.ch[k-i+1]=s.ch[k];str.len=j;return str;}SqString InsStr(SqString s1,int i,SqString s2){int j;SqString str;str.len=0;if (i<=0 || i>s1.len+1) /*参数不正确时返回空串*/{printf("参数不正确\n");return s1;}for (j=0;j<i-1;j++) /*将s1.ch[0]~s1.ch[i-2]复制到str*/str.ch[j]=s1.ch[j];for (j=0;j<s2.len;j++) /*将s2.ch[0]~s2.ch[s2.len-1]复制到str*/str.ch[i+j-1]=s2.ch[j];for (j=i-1;j<s1.len;j++) /*将s1.ch[i-1]~s.ch[s1.len-1]复制到str*/str.ch[s2.len+j]=s1.ch[j];str.len=s1.len+s2.len;return str;}SqString DelStr(SqString s,int i,int j){int k;SqString str;str.len=0;if (i<=0 || i>s.len || i+j>s.len+1) /*参数不正确时返回空串*/{printf("参数不正确\n");return str;}for (k=0;k<i-1;k++) /*将s.ch[0]~s.ch[i-2]复制到str*/str.ch[k]=s.ch[k];for (k=i+j-1;k<s.len;k++)/*将s.ch[i+j-1]~ch[s.len-1]复制到str*/ str.ch[k-j]=s.ch[k];str.len=s.len-j;return str;}SqString RepStr(SqString s,int i,int j,SqString t){int k;SqString str;str.len=0;if (i<=0 || i>s.len || i+j-1>s.len) /*参数不正确时返回空串*/ {printf("参数不正确\n");return str;}for (k=0;k<i-1;k++) /*将s.ch[0]~s.ch[i-2]复制到str*/str.ch[k]=s.ch[k];for (k=0;k<t.len;k++) /*将t.ch[0]~t.ch[t.len-1]复制到str*/str.ch[i+k-1]=t.ch[k];for (k=i+j-1;k<s.len;k++) /*将s.ch[i+j-1]~ch[s.len-1]复制到str*/str.ch[t.len+k-j]=s.ch[k];str.len=s.len-j+t.len;return str;}void DispStr(SqString str){int i;if (str.len>0){for (i=0;i<str.len;i++)printf("%c",str.ch[i]);printf("\n");}}实验题4.2实现链串各种基本运算的算法*文件名:algo4-2.cpp*/#include <stdio.h>#include <malloc.h>typedef struct snode{char data;struct snode *next;} LiString;void StrAssign(LiString *&s,char t[]){int i;LiString *r,*p;s=(LiString *)malloc(sizeof(LiString));s->next=NULL;r=s;for (i=0;t[i]!='\0';i++){p=(LiString *)malloc(sizeof(LiString));p->data=t[i];p->next=NULL;r->next=p;r=p;}}void StrCopy(LiString *&s,LiString *t){LiString *p=t->next,*q,*r;s=(LiString *)malloc(sizeof(LiString));s->next=NULL;s->next=NULL;r=s;while (p!=NULL) /*将t的所有结点复制到s*/{q=(LiString *)malloc(sizeof(LiString));q->data=p->data;q->next=NULL;r->next=q;r=q;p=p->next;}}int StrEqual(LiString *s,LiString *t){LiString *p=s->next,*q=t->next;while (p!=NULL && q!=NULL && p->data==q->data){p=p->next;q=q->next;}if (p==NULL && q==NULL)return 1;elsereturn 0;}int StrLength(LiString *s){int i=0;LiString *p=s->next;while (p!=NULL){i++;p=p->next;}return i;}LiString *Concat(LiString *s,LiString *t){LiString *str,*p=s->next,*q,*r;str=(LiString *)malloc(sizeof(LiString));str->next=NULL;r=str;while (p!=NULL) /*将s的所有结点复制到str*/ {q=(LiString *)malloc(sizeof(LiString));q->data=p->data;q->next=NULL;r->next=q;r=q;p=p->next;}p=t->next;while (p!=NULL) /*将t的所有结点复制到str*/ {q=(LiString *)malloc(sizeof(LiString));q->data=p->data;q->next=NULL;r->next=q;r=q;p=p->next;}return str;}LiString *SubStr(LiString *s,int i,int j){int k;LiString *str,*p=s->next,*q,*r;str=(LiString *)malloc(sizeof(LiString));str->next=NULL;r=str;if (i<=0 || i>StrLength(s) || j<0 || i+j-1>StrLength(s)) {printf("参数不正确\n");return str; /*参数不正确时返回空串*/ }for (k=0;k<i-1;k++)p=p->next;for (k=1;k<=j;k++) /*将s的第i个结点开始的j个结点复制到str*/{q=(LiString *)malloc(sizeof(LiString));q->data=p->data;q->next=NULL;r->next=q;r=q;p=p->next;}return str;}LiString *InsStr(LiString *s,int i,LiString *t){int k;LiString *str,*p=s->next,*p1=t->next,*q,*r;str=(LiString *)malloc(sizeof(LiString));str->next=NULL;r=str;if (i<=0 || i>StrLength(s)+1) /*参数不正确时返回空串*/{printf("参数不正确\n");return str;}for (k=1;k<i;k++) /*将s的前i个结点复制到str*/{q=(LiString *)malloc(sizeof(LiString));q->data=p->data;q->next=NULL;r->next=q;r=q;p=p->next;}while (p1!=NULL) /*将t的所有结点复制到str*/ {q=(LiString *)malloc(sizeof(LiString));q->data=p1->data;q->next=NULL;r->next=q;r=q;p1=p1->next;}while (p!=NULL) /*将*p及其后的结点复制到str*/ {q=(LiString *)malloc(sizeof(LiString));q->data=p->data;q->next=NULL;r->next=q;r=q;p=p->next;}return str;}LiString *DelStr(LiString *s,int i,int j){int k;LiString *str,*p=s->next,*q,*r;str=(LiString *)malloc(sizeof(LiString));str->next=NULL;r=str;if (i<=0 || i>StrLength(s) || j<0 || i+j-1>StrLength(s)) {printf("参数不正确\n");return str; /*参数不正确时返回空串*/ }for (k=0;k<i-1;k++) /*将s的前i-1个结点复制到str*/{q=(LiString *)malloc(sizeof(LiString));q->data=p->data;q->next=NULL;r->next=q;r=q;p=p->next;}for (k=0;k<j;k++) /*让p沿next跳j个结点*/p=p->next;while (p!=NULL) /*将*p及其后的结点复制到str*/{q=(LiString *)malloc(sizeof(LiString));q->data=p->data;q->next=NULL;r->next=q;r=q;p=p->next;}return str;}LiString *RepStr(LiString *s,int i,int j,LiString *t){int k;LiString *str,*p=s->next,*p1=t->next,*q,*r;str=(LiString *)malloc(sizeof(LiString));str->next=NULL;r=str;if (i<=0 || i>StrLength(s) || j<0 || i+j-1>StrLength(s)) {printf("参数不正确\n");return str; /*参数不正确时返回空串*/ }for (k=0;k<i-1;k++) /*将s的前i-1个结点复制到str*/{q=(LiString *)malloc(sizeof(LiString));q->data=p->data;q->next=NULL;r->next=q;r=q;p=p->next;}for (k=0;k<j;k++) /*让p沿next跳j个结点*/p=p->next;while (p1!=NULL) /*将t的所有结点复制到str*/{q=(LiString *)malloc(sizeof(LiString));q->data=p1->data;q->next=NULL;r->next=q;r=q;p1=p1->next;}while (p!=NULL) /*将*p及其后的结点复制到str*/{q=(LiString *)malloc(sizeof(LiString));q->data=p->data;q->next=NULL;r->next=q;r=q;p=p->next;}return str;}void DispStr(LiString *s){LiString *p=s->next;while (p!=NULL){printf("%c",p->data);p=p->next;}printf("\n");}第5章数组和稀疏矩阵——上机实验题5解析实验题5.1求5×5阶螺旋方阵/*文件名:exp5-1.cpp*/#include <stdio.h>#define MaxLen 10void fun(int a[MaxLen][MaxLen],int n){int i,j,k=0,m;if (n%2==0) //m=én/2ùm=n/2;elsem=n/2+1;for (i=0;i<m;i++){for (j=i;j<n-i;j++){k++;a[i][j]=k;}for (j=i+1;j<n-i;j++){k++;a[j][n-i-1]=k;}for (j=n-i-2;j>=i;j--){k++;a[n-i-1][j]=k;}for (j=n-i-2;j>=i+1;j--){k++;a[j][i]=k;}}}void main(){int n,i,j;int a[MaxLen][MaxLen];printf("\n");printf("输入n(n<10):");scanf("%d",&n);fun(a,n);printf("%d阶数字方阵如下:\n",n);for (i=0;i<n;i++){for (j=0;j<n;j++)printf("%4d",a[i][j]);printf("\n");}printf("\n");}实验题5.2求一个矩阵的马鞍点/*文件名:exp5-2.cpp*/#include <stdio.h>#define M 4#define N 4void MinMax(int A[M][N]){int i,j,have=0;int min[M],max[N];for (i=0;i<M;i++) /*计算出每行的最小值元素,放入min[0..M-1]之中*/{min[i]=A[i][0];for (j=1;j<N;j++)if (A[i][j]<min[i])min[i]=A[i][j];}for (j=0;j<N;j++) /*计算出每列的最大值元素,放入max[0..N-1]之中*/{max[j]=A[0][j];for (i=1;i<M;i++)if (A[i][j]>max[j])max[j]=A[i][j];}for (i=0;i<M;i++)for (j=0;j<N;j++)if (min[i]==max[j]){printf(" A[%d,%d]=%d\n",i,j,A[i][j]); /*显示马鞍点*/have=1;}if (!have)printf("没有鞍点\n");}void main(){int i,j;int A[M][N]={{9, 7, 6, 8},{20,26,22,25},{28,36,25,30},{12,4, 2, 6}};printf("A矩阵:\n");for (i=0;i<M;i++){for (j=0;j<N;j++)printf("%4d",A[i][j]);printf("\n");}printf("A矩阵中的马鞍点:\n");MinMax(A); /*调用MinMax()找马鞍点*/}实验题5.3求两个对称矩阵之和与乘积/*文件名:exp5-3.cpp*/#include <stdio.h>#define n 4#define m 10int value(int a[],int i,int j){if (i>=j)return a[(i*(i-1))/2+j];elsereturn a[(j*(j-1))/2+i];}void madd(int a[],int b[],int c[n][n]){int i,j;for (i=0;i<n;i++)for (j=0;j<n;j++)c[i][j]=value(a,i,j)+value(b,i,j);}void mult(int a[],int b[],int c[n][n]){int i,j,k,s;for (i=0;i<n;i++)for (j=0;j<n;j++){s=0;for (k=0;k<n;k++)s=s+value(a,i,k)*value(b,k,j); c[i][j]=s;}}void disp1(int a[]){int i,j;for (i=0;i<n;i++){for (j=0;j<n;j++)printf("%4d",value(a,i,j));printf("\n");}}void disp2(int c[n][n]){int i,j;for (i=0;i<n;i++){for (j=0;j<n;j++)printf("%4d",c[i][j]);printf("\n");}}void main(){int a[m]={1,2,3,4,5,6,7,8,9,10};int b[m]={1,1,1,1,1,1,1,1,1,1};int c1[n][n],c2[n][n];madd(a,b,c1);mult(a,b,c2);printf("\n");printf("a矩阵:\n");disp1(a);printf("b矩阵:\n");disp1(b);printf("a+b:\n");disp2(c1);printf("a*b:\n");disp2(c2);printf("\n");}实验题5.4实现稀疏矩阵(采用三元组表示)的基本运算/*文件名:exp5-4.cpp*/#include <stdio.h>#define N 4typedef int ElemType;#define MaxSize 100 /*矩阵中非零元素最多个数*/ typedef struct{ int r; /*行号*/int c; /*列号*/ElemType d; /*元素值*/} TupNode; /*三元组定义*/typedef struct{ int rows; /*行数值*/int cols; /*列数值*/int nums; /*非零元素个数*/TupNode data[MaxSize];} TSMatrix; /*三元组顺序表定义*/void CreatMat(TSMatrix &t,ElemType A[N][N]){int i,j;t.rows=N;t.cols=N;t.nums=0;for (i=0;i<N;i++){for (j=0;j<N;j++)if (A[i][j]!=0){t.data[t.nums].r=i;t.data[t.nums].c=j;t.data[t.nums].d=A[i][j];t.nums++;}}}void DispMat(TSMatrix t){int i;if (t.nums<=0)return;printf("\t%d\t%d\t%d\n",t.rows,t.cols,t.nums);printf("\t------------------\n");for (i=0;i<t.nums;i++)printf("\t%d\t%d\t%d\n",t.data[i].r,t.data[i].c,t.data[i].d); }void TranMat(TSMatrix t,TSMatrix &tb){int p,q=0,v; /*q为tb.data的下标*/tb.rows=t.cols;tb.cols=t.rows;tb.nums=t.nums;if (t.nums!=0){for (v=0;v<t.cols;v++) /*tb.data[q]中的记录以c 域的次序排列*/for (p=0;p<t.nums;p++) /*p为t.data的下标*/if (t.data[p].c==v){tb.data[q].r=t.data[p].c;tb.data[q].c=t.data[p].r;tb.data[q].d=t.data[p].d;q++;}}}int MatAdd(TSMatrix a,TSMatrix b,TSMatrix &c){int i=0,j=0,k=0;ElemType v;if (a.rows!=b.rows || a.cols!=b.cols)return 0; /*行数或列数不等时不能进行相加运算*/c.rows=a.rows;c.cols=a.cols; /*c的行列数与a的相同*/while (i<a.nums && j<b.nums) /*处理a和b中的每个元素*/{if (a.data[i].r==b.data[j].r) /*行号相等时*/{if(a.data[i].c<b.data[j].c) /*a元素的列号小于b 元素的列号*/{c.data[k].r=a.data[i].r;/*将a元素添加到c中*/c.data[k].c=a.data[i].c;c.data[k].d=a.data[i].d;k++;i++;}else if (a.data[i].c>b.data[j].c)/*a元素的列号大于b元素的列号*/{c.data[k].r=b.data[j].r; /*将b元素添加到c中*/c.data[k].c=b.data[j].c;c.data[k].d=b.data[j].d;k++;j++;}else /*a元素的列号等于b元素的列号*/{v=a.data[i].d+b.data[j].d;if (v!=0) /*只将不为0的结果添加到c中*/{c.data[k].r=a.data[i].r;c.data[k].c=a.data[i].c;c.data[k].d=v;k++;}i++;j++;}}else if (a.data[i].r<b.data[j].r) /*a元素的行号小于b元素的行号*/{c.data[k].r=a.data[i].r; /*将a元素添加到c中*/c.data[k].c=a.data[i].c;c.data[k].d=a.data[i].d;k++;i++;}else /*a元素的行号大于b元素的行号*/{c.data[k].r=b.data[j].r; /*将b元素添加到c中*/c.data[k].c=b.data[j].c;c.data[k].d=b.data[j].d;k++;j++;}c.nums=k;}return 1;}int value(TSMatrix c,int i,int j){int k=0;while (k<c.nums && (c.data[k].r!=i || c.data[k].c!=j))k++;if (k<c.nums)return(c.data[k].d);elsereturn(0);}int MatMul(TSMatrix a,TSMatrix b,TSMatrix &c){int i,j,k,p=0;ElemType s;if (a.cols!=b.rows) /*a的列数不等于b的行数时不能进行相乘运算*/return 0;for (i=0;i<a.rows;i++)for (j=0;j<b.cols;j++){s=0;for (k=0;k<a.cols;k++)s=s+value(a,i,k)*value(b,k,j);if (s!=0) /*产生一个三元组元素*/{c.data[p].r=i;c.data[p].c=j;c.data[p].d=s;p++;}}c.rows=a.rows;c.cols=b.cols;c.nums=p;return 1;}void main(){ElemType a1[N][N]={{1,0,3,0},{0,1,0,0},{0,0,1,0},{0,0,1,1}};ElemType b1[N][N]={{3,0,0,0},{0,4,0,0},{0,0,1,0},{0,0,0,2}};TSMatrix a,b,c;CreatMat(a,a1);CreatMat(b,b1);printf("a的三元组:\n");DispMat(a);printf("b的三元组:\n");DispMat(b);printf("a转置为c\n");TranMat(a,c);printf("c的三元组:\n");DispMat(c);printf("c=a+b\n");MatAdd(a,b,c);printf("c的三元组:\n");DispMat(c);printf("c=a*b\n");MatMul(a,b,c);printf("c的三元组:\n");DispMat(c);}实验题5.5实现广义表的基本运算#include <stdio.h>#include <malloc.h>typedef char ElemType;typedef struct lnode{ int tag; /*结点类型标识*/ union{ElemType data;struct lnode *sublist;}val;struct lnode *link; /*指向下一个元素*/} GLNode;extern GLNode *CreatGL(char *&s);extern void DispGL(GLNode *g);void Change(GLNode *&g,ElemType s,ElemType t) /*将广义表g中所有原子s 替换成t*/{if (g!=NULL){if (g->tag==1) /*子表的情况*/Change(g->val.sublist,s,t);else if (g->val.data==s) /*原子且data域值为s的情况*/g->val.data=t;Change(g->link,s,t);}}void Reverse(GLNode *&g) /*将广义表g所有元素逆置*/{GLNode *p,*q,*t;t=NULL;if (g!=NULL){p=g;while (p!=NULL) /*将同级的兄弟逆置*/{q=p->link;if (t==NULL){t=p;p->link=NULL;}else{p->link=t;t=p;}p=q;}g=t;p=g;while (p!=NULL){if (p->tag==1)Reverse(p->val.sublist);p=p->link;}}}int Same(GLNode *g1,GLNode *g2) /*判断两个广义表是否相同*/ {int s;if (g1==NULL && g2==NULL) /*均为NULL的情况*/return 1;else if ((g1==NULL && g2!=NULL) || (g1!=NULL && g2==NULL)) /*一个为NULL,另一不为NULL的情况*/return 0;else{s=1;while (g1!=NULL && g2!=NULL && s==1){if (g1->tag==1 && g2->tag==1)/*均为子表的情况*/s=Same(g1->val.sublist,g2->val.sublist);else if (g1->tag==0 && g2->tag==0)/*均为原子的情况*/{if (g1->val.data!=g2->val.data)s=0;}else /*一个为原子,另一为子表的情况*/s=0;g1=g1->link;g2=g2->link;}if (g1!=NULL || g2!=NULL) /*有一个子表尚未比较完时*/s=0;return s;}}ElemType MaxAtom(GLNode *g) /*求广义表g中最大的原子*/{ElemType m=0,m1; /*m赋初值0*/while (g!=NULL){if (g->tag==1) /*子表的情况*/{m1=MaxAtom(g->val.sublist); /*对子表递归调用*/if (m1>m) m=m1;}else{if (g->val.data>m) /*为原子时,进行原子比较*/m=g->val.data;}g=g->link;}return m;}void DelAtom(GLNode *&g,ElemType x) /*删除广义表g中的第一个为x原子*/{GLNode *p=g,*q,*pre;while (p!=NULL){q=p->link;if (p->tag==1) /*子表的情况*/DelAtom(p->val.sublist,x); /*对子表递归调用*/else{if (p->val.data==x) /*为原子时,进行原子比较*/{if (p==g)/*被删结点是本层的第1个结点*/{g=q;free(p); /*释放结pre=g;}else /*被删结{pre->link=q;free(p);}return;}}pre=p;p=q;}}void DelAtomAll(GLNode *&g,ElemType x) /*删除广义表g中的所有为x原子*/{GLNode *p=g,*q,*pre;while (p!=NULL){q=p->link;if (p->tag==1) /*子表的情况*/DelAtomAll(p->val.sublist,x); /*对子表递归调用*/else{if (p->val.data==x) /*为原子时,进行原子比较*/if (p==g)/*被删结点是本层的第1个结点*/{g=q;free(p); /*释放结pre=g;}else /*被删结{pre->link=q;free(p);}}pre=p;p=q;}}void PreOrder(GLNode *g) /*采用先根遍历g*/{if (g!=NULL){if (g->tag==0) /*为原子结点时*/printf("%c ",g->val.data);elsePreOrder(g->val.sublist); /*为子表时*/ PreOrder(g->link);}}void main(){GLNode *g1,*g2,*g3,*g4;char *str1="(a,(a),((a,b)),((a)),a)";char *str2="(a,(b),((c,d)),((e)),f)";char *str3="(a,(a,b),(a,b,c)))";char *str4="(a,(b),((c,d)),((e)),f)";g1=CreatGL(str1);printf("\n");printf(" 广义表g1:");DispGL(g1);printf("\n");printf(" 将广义表g1中所有'a'改为'b'\n");Change(g1,'a','b');printf(" 广义表g1:");DispGL(g1);printf("\n\n");g2=CreatGL(str2);printf(" 广义表g2:");DispGL(g2);printf("\n");printf(" 广义表g2中最大原子:%c\n",MaxAtom(g2));printf(" 将g2的元素逆置\n");Reverse(g2);printf(" 广义表g2:");DispGL(g2);printf("\n\n");printf(" 广义表g1和g2%s\n\n",(Same(g1,g2)?"相同":"不相同"));g3=CreatGL(str3);printf(" 广义表g3:");DispGL(g3);printf("\n");printf(" 删除广义表g3的第一个为'a'的原子\n");DelAtom(g3,'a');printf(" 广义表g3:");DispGL(g3);printf("\n\n");printf(" 删除广义表g3中的所有'a'原子\n");DelAtomAll(g3,'a');printf(" 广义表g3:");DispGL(g3);printf("\n\n");g4=CreatGL(str4);printf(" 广义表g4:");DispGL(g4);printf("\n");printf(" 采用先根遍历g4的结果:");PreOrder(g4);printf("\n\n");}。
数据结构实验报告 答案

数据结构实验报告答案一、实验目的本次数据结构实验的主要目的是通过实际编程和操作,深入理解和掌握常见的数据结构,如数组、链表、栈、队列、树和图等,并能够运用这些数据结构解决实际问题,提高编程能力和算法设计能力。
二、实验环境操作系统:Windows 10编程语言:C++开发工具:Visual Studio 2019三、实验内容1、数组操作定义一个整数数组,实现数组元素的输入、输出和查找功能。
对数组进行排序(选择排序、冒泡排序等),并输出排序后的数组。
2、链表操作构建一个单向链表,实现链表节点的插入、删除和遍历操作。
反转链表,并输出反转后的链表。
3、栈和队列操作用数组实现栈和队列的数据结构,实现入栈、出栈、入队、出队等基本操作。
利用栈实现表达式求值(中缀表达式转后缀表达式,然后计算后缀表达式的值)。
4、树的操作构建二叉树(可以采用顺序存储或链式存储),实现二叉树的前序、中序和后序遍历。
实现二叉树的查找、插入和删除节点操作。
5、图的操作用邻接矩阵或邻接表表示图,实现图的深度优先遍历和广度优先遍历。
求解图的最短路径(Dijkstra 算法或 Floyd 算法)。
四、实验步骤及代码实现1、数组操作```cppinclude <iostream>using namespace std;//数组输入函数void inputArray(int arr, int size) {cout <<"请输入"<< size <<"个整数:"<< endl; for (int i = 0; i < size; i++){cin >> arri;}}//数组输出函数void outputArray(int arr, int size) {cout <<"数组元素为:"<< endl;for (int i = 0; i < size; i++){cout << arri <<"";}cout << endl;}//数组查找函数int searchArray(int arr, int size, int target) {for (int i = 0; i < size; i++){if (arri == target) {return i;}}return -1;}//选择排序函数void selectionSort(int arr, int size) {for (int i = 0; i < size 1; i++){int minIndex = i;for (int j = i + 1; j < size; j++){if (arrj < arrminIndex) {minIndex = j;}}if (minIndex!= i) {int temp = arri;arri = arrminIndex;arrminIndex = temp;}}}//冒泡排序函数void bubbleSort(int arr, int size) {for (int i = 0; i < size 1; i++){for (int j = 0; j < size i 1; j++){if (arrj > arrj + 1) {int temp = arrj;arrj = arrj + 1;arrj + 1 = temp;}}}}int main(){int size = 10;inputArray(arr, size);outputArray(arr, size);int target = 5;int result = searchArray(arr, size, target);if (result!=-1) {cout <<"找到目标元素"<< target <<",在数组中的索引为"<< result << endl;} else {cout <<"未找到目标元素"<< target << endl;}selectionSort(arr, size);outputArray(arr, size);bubbleSort(arr, size);outputArray(arr, size);return 0;}2、链表操作```cppinclude <iostream>using namespace std;//链表节点结构体struct ListNode {int data;ListNode next;ListNode(int x) : data(x), next(NULL) {}};//链表插入函数void insertNode(ListNode& head, int val) {ListNode newNode = new ListNode(val);if (head == NULL) {head = newNode;return;}ListNode curr = head;while (curr>next!= NULL) {curr = curr>next;}curr>next = newNode;}//链表删除函数void deleteNode(ListNode& head, int val) {if (head == NULL) {return;}if (head>data == val) {ListNode temp = head;head = head>next;delete temp;return;}ListNode curr = head;while (curr>next!= NULL && curr>next>data!= val) {curr = curr>next;}if (curr>next!= NULL) {ListNode temp = curr>next;curr>next = curr>next>next;delete temp;}}//链表遍历函数void traverseList(ListNode head) {ListNode curr = head;while (curr!= NULL) {cout << curr>data <<"";curr = curr>next;}cout << endl;}//链表反转函数ListNode reverseList(ListNode head) {ListNode prev = NULL;ListNode curr = head;while (curr!= NULL) {ListNode nextTemp = curr>next; curr>next = prev;prev = curr;curr = nextTemp;}return prev;}int main(){ListNode head = NULL;insertNode(head, 1);insertNode(head, 2);insertNode(head, 3);insertNode(head, 4);insertNode(head, 5);traverseList(head);deleteNode(head, 3);traverseList(head);ListNode reversedHead = reverseList(head);traverseList(reversedHead);return 0;}```3、栈和队列操作```cppinclude <iostream>using namespace std;//用数组实现栈const int MAX_SIZE = 100;class Stack {private:int arrMAX_SIZE;int top;public:Stack(){top =-1;}//入栈void push(int val) {if (top == MAX_SIZE 1) {cout <<"栈已满,无法入栈" << endl; return;}arr++top = val;}//出栈int pop(){if (top ==-1) {cout <<"栈为空,无法出栈" << endl; return -1;}int val = arrtop;top;return val;}//查看栈顶元素int peek(){if (top ==-1) {cout <<"栈为空" << endl;return -1;}return arrtop;}//判断栈是否为空bool isEmpty(){return top ==-1;}};//用数组实现队列class Queue {private:int arrMAX_SIZE;int front, rear;public:Queue(){front = rear =-1;}//入队void enqueue(int val) {if ((rear + 1) % MAX_SIZE == front) {cout <<"队列已满,无法入队" << endl; return;}if (front ==-1) {front = 0;}rear =(rear + 1) % MAX_SIZE;arrrear = val;}//出队int dequeue(){if (front ==-1) {cout <<"队列为空,无法出队" << endl; return -1;}int val = arrfront;if (front == rear) {front = rear =-1;} else {front =(front + 1) % MAX_SIZE;}return val;}//查看队头元素int peek(){if (front ==-1) {cout <<"队列为空" << endl;return -1;}return arrfront;}//判断队列是否为空bool isEmpty(){return front ==-1;}};//表达式求值函数int evaluateExpression(string expression) {Stack operandStack;Stack operatorStack;for (int i = 0; i < expressionlength(); i++){char c = expressioni;if (isdigit(c)){int operand = 0;while (i < expressionlength()&& isdigit(expressioni)){operand = operand 10 +(expressioni++'0');}i;operandStackpush(operand);} else if (c =='+'|| c ==''|| c ==''|| c =='/'){while (!operatorStackisEmpty()&&precedence(operatorStackpeek())>= precedence(c)){int operand2 = operandStackpop();int operand1 = operandStackpop();char op = operatorStackpop();int result = performOperation(operand1, operand2, op);operandStackpush(result);}operatorStackpush(c);} else if (c =='('){operatorStackpush(c);} else if (c ==')'){while (operatorStackpeek()!='('){int operand2 = operandStackpop();int operand1 = operandStackpop();char op = operatorStackpop();int result = performOperation(operand1, operand2, op);operandStackpush(result);}operatorStackpop();}}while (!operatorStackisEmpty()){int operand2 = operandStackpop();int operand1 = operandStackpop();char op = operatorStackpop();int result = performOperation(operand1, operand2, op);operandStackpush(result);}return operandStackpop();}//运算符优先级函数int precedence(char op) {if (op =='+'|| op ==''){return 1;} else if (op ==''|| op =='/'){return 2;}return 0;}//运算函数int performOperation(int operand1, int operand2, char op) {switch (op) {case '+':return operand1 + operand2;case '':return operand1 operand2;case '':return operand1 operand2;case '/':if (operand2!= 0) {return operand1 / operand2;} else {cout <<"除数不能为 0" << endl;return -1;}}return -1;}int main(){Stack stack;stackpush(1);stackpush(2);stackpush(3);cout <<"栈顶元素:"<< stackpeek()<< endl;cout <<"出栈元素:"<< stackpop()<< endl;cout <<"栈是否为空:"<<(stackisEmpty()?"是" :"否")<< endl;Queue queue;queueenqueue(1);queueenqueue(2);queueenqueue(3);cout <<"队头元素:"<< queuepeek()<< endl;cout <<"出队元素:"<< queuedequeue()<< endl;cout <<"队列是否为空:"<<(queueisEmpty()?"是" :"否")<< endl;string expression ="2+34";int result = evaluateExpression(expression);cout << expression <<"="<< result << endl; return 0;}```4、树的操作```cppinclude <iostream>using namespace std;//二叉树节点结构体struct TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};//前序遍历函数void preOrderTraversal(TreeNode root) {return;}cout << root>val <<"";preOrderTraversal(root>left);preOrderTraversal(root>right);}//中序遍历函数void inOrderTraversal(TreeNode root) {if (root == NULL) {return;}inOrderTraversal(root>left);cout << root>val <<"";inOrderTraversal(root>right);}//后序遍历函数void postOrderTraversal(TreeNode root) {return;}postOrderTraversal(root>left);postOrderTraversal(root>right);cout << root>val <<"";}//查找函数TreeNode searchBST(TreeNode root, int val) {if (root == NULL || root>val == val) {return root;}if (val < root>val) {return searchBST(root>left, val);} else {return searchBST(root>right, val);}}//插入函数TreeNode insertBST(TreeNode root, int val) {if (root == NULL) {return new TreeNode(val);}if (val < root>val) {root>left = insertBST(root>left, val);} else if (val > root>val) {root>right = insertBST(root>right, val);}return root;}//删除函数TreeNode deleteNodeBST(TreeNode root, int key) {if (root == NULL) {return root;}if (key < root>val) {root>left = deleteNodeBST(root>left, key);} else if (key > root>val) {root>right = deleteNodeBST(root>right, key);} else {if (root>left == NULL) {TreeNode temp = root>right;delete root;return temp;} else if (root>right == NULL) {TreeNode temp = root>left;delete root;return temp;}TreeNode minNode = root>right;while (minNode>left!= NULL) {minNode = minNode>left;}root>val = minNode>val;root>right = deleteNodeBST(root>right, minNode>val);}return root;}int main(){TreeNode root = new TreeNode(4);root>left = new TreeNode(2);root>right = new TreeNode(6);root>left>left = new TreeNode(1);root>left>right = new TreeNode(3);root>right>left = new TreeNode(5);root>right>right = new TreeNode(7);cout <<"前序遍历:"<< endl; preOrderTraversal(root);cout << endl;cout <<"中序遍历:"<< endl; inOrderTraversal(root);cout << endl;cout <<"后序遍历:"<< endl; postOrderTraversal(root);cout << endl;int target = 3;TreeNode foundNode = searchBST(root, target);if (foundNode!= NULL) {cout <<"找到目标节点"<< target << endl;} else {cout <<"未找到目标节点"<< target << endl;}root = insertBST(root, 8);cout <<"插入节点 8 后的中序遍历:"<< endl; inOrderTraversal(root);cout << endl;root = deleteNodeBST(root, 2);cout <<"删除节点 2 后的中序遍历:。
数据结构实践题及答案

重庆邮电学院软件学院《数据结构》实验参考资料<适用于软件学院13104级>重庆邮电学院软件学院实验中心目录一、课程编号 (2)二、课程类型 (2)三、本课程的地位、作用与任务 (2)四、课程基本要求 (2)五、实验安排 (2)1、数据结构实验机器与环境 (2)(一)计算机的硬件配置 (2)(二)计算机的软件配置 (2)2、VisualC++6.0开发C语言程序 (2)(一)进入C++工作环境 (2)(二)编译、运行C程序 (3)3、上机实验 (6)实验1:线性表操作 (6)实验2:单链表操作 (11)实验3:表达式计算 (17)实验4:二叉树操作 (24)实验5:二叉搜索树操作 (30)实验6:图的运算 (36)实验7:散列表操作 (43)实验8:外存文件的排序操作 (49)实验9:二叉搜索树与文件操作 (53)六、教材 (60)七、成绩考核办法 (60)数据结构(C语言版)实验一、课程编号130101(本科)二、课程类型课程类型:必修课。
适用专业:计算机系各专业实验学时:10学时三、本课程的地位、作用与任务《数据结构》在计算机科学中是一门综合性的专业基础课。
数据结构的研究不仅涉及到计算机硬件的研究范围,而且和计算机软件的研究有密切的关系,可以认为数据结构是介于数学、计算机硬件和计算机软件三者之间的一门核心课程。
在计算机科学中,数据结构不仅是一般程序设计的基础,而且是设计和实现编译程序、操作系统、数据库系统及其它系统程序和大型应用程序的重要基础,它的主要任务是讨论各种数据结构的逻辑结构,存储结构及有关操作的算法。
目的是使学生学会分析研究计算机加工的数据结构的特性,以便为应用涉及的数据选择适当的逻辑结构、存储结构及相应的算法,并初步了解对算法的时间分析和空间分析技术。
另一方面,通过对本课程算法设计和上机实践的训练,还应培养学生的数据抽象能力和程序设计的能力。
从而为提高学生的实际分析问题和解决问题的编程能力打下基础。
数据结构(含上机实训)课后题答案

*e =Q->elem[tmpfront];//用e返回队头元素
}
一、填空题
1.串中的元素为字符型数据
2.两个串的长度相等,并且各个对应位置的字符都相等
3.定长顺序存储,堆存储,块链存储,堆存储
4.1100
str2[k ++] = str1[i ++];
else
{
if (Isoperator (str1[i]) == -1)//如果读入字符不是操作符,则出错
return ERROR;
switch (Compare (GetTop (OPTR), str[i]))//比较操作符优先级高低
{
case '<'://读入字符优先级高于栈顶字符优先级
OPTR栈
OPND栈
当前读入字符
步骤
OPTR栈
OPND栈
当前读入字符
1
#
35
8
# - /
35 50
2
2
#
35
-
9
# - /
35 50 2
+
3
# -
35
5
10
# -
35 25
+
4
# -
35 5
*
11
#
10
+
5
# - *
35 5
10
12
# +
10
5
6
# - *
35 5 10
/
13
# +
10 5
#
7
# -
break;
default:
Push(&S,ch);//输入其他字符直接进栈
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
《数据结构实验指导书》答案实验一:1、请编写函数int fun(int *a, int *b),函数的功能是判断两个指针a和b所指存储单元的值的符号是否相同;若相同函数返回1,否则返回0。
这两个存储单元中的值都不为0。
在主函数中输入2个整数、调用函数fun、输出结果。
#include <stdio.h>int fun(int *a, int *b){if (*a*(*b)>0) return(1);else return(0);}main(){int x,y;scanf("%d%d",&x,&y);if (fun(&x,&y)) printf("yes\n");else printf("no");}2、计算1+2+3+……+100,要求用指针进行设计。
即设计函数int fun(int *n)实现求1+2+3+……+*n,在主函数中输入、调用、输出结果。
#include <stdio.h>int fun(int *n){int i,sum=0;for (i=1;i<=*n;i++)sum+=i;return(sum);}main(){int x,sum;scanf("%d",&x);printf("the sum is %d\n",fun(&x));}3、函数的功能是求数组a中最大数的位置(位序号)。
在主函数中输入10个整数、调用函数fun、输出结果。
#define N 10#include <stdio.h>void input(int *a,int n){int i;for (i=0;i<n;i++)scanf("%d",a+i); /*scanf("%d",&a[i]);*/}int fun(int *a,int n){int i,*max;max=a;for (i=1;i<n;i++)if (a[i]>*max) max=a+i;return(max-a);}main(){int a[N],maxi;input(a,N);maxi=fun(a,N);printf("\n the max position is %d\n",maxi);}4、请编写函数fun(int *a,int n, int *odd, int *even),函数的功能是分别求出数组a中所有奇数之和和所有偶数之和。
形参n给出数组中数据的个数;利用指针odd和even分别返回奇数之和和偶数之和。
在主函数中输入10个整数、调用函数fun、输出结果。
#define N 10#include <stdio.h>void input(int *a,int n){int i;for (i=0;i<n;i++)scanf("%d",a+i); /*scanf("%d",&a[i]);*/}void fun(int *a,int n, int *odd, int *even){int i,sum1=0,sum2=0;for (i=0;i<n;i++){if (a[i]%2==0) sum1+=a[i];else sum2+=a[i];}*odd=sum1;*even=sum2;}main(){int a[N],odd,even;input(a,N);fun(a,N, &odd, &even);printf("the odd is %d\tthe even is %d\n",odd,even);}5、请编写函数int fun(int *a, int *b,int n),函数的功能是把数组a中所有为偶数的数,放在另一个数组中b。
在主函数中输入10个整数、调用函数fun、输出结果。
#define N 10#include <stdio.h>void input(int *a,int n){int i;for (i=0;i<n;i++)scanf("%d",a+i); /*scanf("%d",&a[i]);*/}void output(int *a,int n){int i;printf("\nthe odd is:\n");for (i=0;i<n;i++)printf("%5d",*(a+i)); /*printf("%d",a[i]);*/}int fun(int *a, int *b,int n){int i,j=0;for (i=0;i<n;i++)if (a[i]%2==0) { b[j]=a[i]; j++;}return(j);main(){int a[N],b[N],m;input(a,N);m=fun(a,b,N);output(b,m);}6、请编写函数int fun(int *a,,int n),函数的功能是把数组a中最大数和最小数交换。
在主函数中输入10个整数、调用函数fun、输出结果。
#define N 10#include <stdio.h>void input(int *a,int n){int i;for (i=0;i<n;i++)scanf("%d",a+i); /*scanf("%d",&a[i]);*/}void output(int *a,int n){int i;printf("\nthe result is:\n");for (i=0;i<n;i++)printf("%5d",*(a+i)); /*printf("%d",a[i]);*/}void fun(int *a,int n){int i,*max,*min,temp;max=min=a;for (i=1;i<n;i++){if (a[i]>*max) max=a+i;if (a[i]<*min) min=a+i;}printf("the max is %d,the position is %d\n",*max,max-a);printf("the min is %d,the position is %d\n",*min,min-a);if (max!=min){temp=*max;*max=*min;*min=temp;}}main(){int a[N],m;input(a,N);fun(a,N);output(a,N);}7、请编写函数int fun(int a[4][4]),函数的功能是把矩阵a转置。
在主函数中输入、调用函数fun、输出结果。
#define N 4#include <stdio.h>void input(int a[][4],int n){int i,j;for (i=0;i<n;i++)for (j=0;j<n;j++)scanf("%d",&a[i][j]);}void output(int a[][4],int n){int i,j;printf("\nthe result is:\n");for (i=0;i<n;i++){printf("\n");for (j=0;j<n;j++)printf("%4d",*(*(a+i)+j)); /*printf("%d",a[i][j]);*/}}void fun(int a[][4],int n){int i,j,temp;for (i=0;i<n;i++)for (j=0;j<i;j++){temp=a[i][j];a[i][j]=a[j][i];a[j][i]=temp;}}main(){int a[N][N];input(a,N);fun(a,N);output(a,N);}8、请编写函数int fun(char *a),函数的功能是分别求出字符串a 的长度。
在主函数中输入1个字符串、调用函数fun、输出结果。
#include <stdio.h>int fun(char *a){int i=0;char *p;p=a;while (*p){i++;p++;}return(i);}main(){char str[20],*cp;cp=str;gets(cp);printf("the length of %s is %d\n",cp,fun(cp));}9、10、#include <stdio.h>#include <string.h>#define N 2typedef struct student /*定义数据结构(数据类型)*/{long num;char name[10];int score[3]; /*存放三门课成绩 */float average; /*/平均成绩*/} stu;void intput(stu s[],int n) /*输入数据 */{int i,j; /*i表示处理学生的下标,J表示成绩编号 */for (i=0;i<n;i++){printf("input num:\n");scanf("%ld",&s[i].num);printf("input name:\n");scanf("%s",s[i].name);printf("input 3 score:\n");for (j=0;j<3;j++)scanf("%d",&s[i].score[j]);}}void stu_av(stu s[],int n)/*求每个学生的平均成绩*/ {int i,j,sum;for (i=0;i<n;i++){sum=0;for (j=0;j<3;j++)sum+=s[i].score[j] ;s[i].average=sum/3.0;}}float av(stu s[],int n)/*求总平均成绩*/{int i;float sum=0.0,ave;for (i=0;i<n;i++)sum+=s[i].average;ave=sum/n;return(ave);}int max(stu s[],int n)/*求平均成绩最高学生的下标*/ {int i,maxi=0;for (i=1;i<n;i++)if (s[i].average>s[maxi].average)maxi=i;return(maxi);}main(){int maxi,j;stu a[N];/*定义变量 */intput(a,N);stu_av(a,N);printf("the score average is %f\n", av(a,N)); maxi=max(a,N);printf("the max average student data:\n");printf("%10ld",a[maxi].num);printf("%10s",a[maxi].name);for (j=0;j<3;j++)printf("%5d",a[maxi].score[j]);printf("%5.1f",a[maxi].average);getch();}实验二1、《数据结构实验指导书》答案实验一:1、请编写函数int fun(int *a, int *b),函数的功能是判断两个指针a和b所指存储单元的值的符号是否相同;若相同函数返回1,否则返回0。