上代码:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <windows.h> #define LIST_INIT_SIZE 100 #define MAXSIZE 100 #define LISTINCREMENT #define OK 1 #define OVERFLOW -1 #define ERROR 0 typedef int ElemType; typedef int Status; typedef struct { ElemType elem[MAXSIZE]; int length; } SqList; int Cheak(SqList * L) { if(!L) { printf("线性表未创建!\n"); return 0; } return 1; } Status InitList(SqList * &L)///构造一个空的线性表 { L =(SqList*)malloc( LIST_INIT_SIZE * sizeof(SqList)); if(!L) exit(OVERFLOW); L->length = 0; return OK; } Status DestroyList(SqList * & L) { free(L); L=NULL; return OK; } void ListEmpty(SqList * L) { if(L->length==0) printf("线性表为空\n"); else printf("线性表非空\n"); } int ListLength(SqList *L) { return L->length; } Status GetElem(SqList *L,int i,int & e) { if(L->length==0) { printf("线性表为空\n"); return ERROR; } if(i<1||i>L->length) { printf("超出范围\n"); return ERROR; } e=L->elem[i-1]; return OK; } Status ListInsert(SqList * L,int i,ElemType e) { int j; if(i<1||i>L->length+1)return ERROR; for( j=L->length-1; j>=i; j--) { L->elem[j+1]=L->elem[j]; } L->elem[j+1]=e; L->length++; return OK; } Status ListDelete(SqList *L,int i,ElemType &e) { if(i<1||i>L->length+1)return ERROR; e=L->elem[i-1]; for(int j=i-1; j<L->length-1; j++) { L->elem[j]=L->elem[j+1]; } L->length--; return OK; } void Display() { system("cls"); printf("1.创建线性表\n"); printf("2.删除线性表\n"); printf("3.线性表是否为空\n"); printf("4.线性表长度\n"); printf("5.获取线性表元素\n"); printf("6.插入元素\n"); printf("7.删除元素\n"); printf("8.遍历线性表\n"); printf("9.退出\n"); } void ListTraverse(SqList *L) { if(L->length==0) printf("线性表为空!!!\n"); else for(int i=0; i<L->length; i++) printf("%d%c",i==(L->length-1) ?‘\n‘:‘ ‘,L->elem[i]); } int main() { SqList *L; L=NULL; int order,e,i; while(1) { Display(); scanf("%d",&order); switch(order) { case 1: InitList(L); break; case 2: if(Cheak(L))DestroyList(L); break; case 3: if(Cheak(L))ListEmpty(L); break; case 4: if(Cheak(L))printf("线性表长度为%d\n",ListLength(L)); break; case 5: if(Cheak(L)) { printf("输入你想获取的元素序号:"); scanf("%d",&i); GetElem(L,i,e); printf("元素为:%d\n",e); } break; case 6: if(Cheak(L)) { printf("输入你想插入的位置和元素:"); scanf("%d%d",&i,&e); ListInsert(L,i,e); } break; case 7: if(Cheak(L)) { printf("输入你想删除的位置和元素:"); scanf("%d%d",&i,&e); ListDelete(L,i,e); } break; case 8: if(Cheak(L))ListTraverse(L); break; default:return 0; } system("pause"); } return 0; }