线性表
1.线性表的抽象数据类型
Status InitList(SqList *L) //构造一个空的线性表 注意定义一个常量OVERFLOW为-1
Status DestoryList(SqList *L) //销毁 注意要置空指针
Status ClearList(SqList *L) //清空
Status ListEmpty(L)
Status ListInsert(SqList *L,int i,ElemType e)
//realloc用法: (void *)realloc("需要回收的内存",number*sizeof(void));
Q1:线性表中第一个数没有打印出来
A1:主函数中for(i=0;i<=10;i++) 插入函数中 函数体内已经减1 所以i应该从1开始
#include<stdio.h> #include<stdlib.h> #define OK 1 #define ERROR 0 #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 #define OVERFLOW -1 #define TRUE 1 #define FALSE 0 typedef int ElemType; typedef int Status; typedef struct { ElemType *elem; int length; int listsize; } SqList; Status InitList(SqList *L) { L->elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType)); if(!L->elem) exit(OVERFLOW); L->length=0; L->listsize=LIST_INIT_SIZE; return OK; } Status DestoryList(SqList *L) { free(L->elem); L->elem=NULL; L->length=0; L->listsize=0; return OK; } Status ClearList(SqList *L) { L->length=0; return OK; } Status ListEmpty(SqList L) { if(L.length==0) return TRUE; else return FALSE; } Status ListLength(SqList L) { return L.length; } Status GetElem(SqList L,int i,ElemType *e) { if(i>L.length||i<=0) return ERROR; *e=L.elem[i-1]; return OK; } Status ListInsert(SqList *L,int i,ElemType e) { int k; ElemType *newbase; if(i<1||i>L->length+1) return ERROR; if(L->length==L->listsize) { newbase=(ElemType *)realloc(L->elem,(L->listsize+LISTINCREMENT*sizeof(ElemType))); if(!newbase) exit(OVERFLOW); L->elem=newbase; L->listsize=L->listsize+LISTINCREMENT; } for(k=L->length-1;k>=i-1;k--) { L->elem[k+1]=L->elem[k]; } L->elem[i-1]=e; L->length++; return OK; } Status ListDelete(SqList *L,int i,ElemType *e) { int k; if(i<1||i>L->length) return ERROR; *e=L->elem[i-1]; for(k=i;k<=L->length-1;k++) L->elem[k-1]=L->elem[k]; L->length--; return OK; } Status ListTraverse(SqList L) { int i; for(i=0;i<L.length;i++) { printf("%3d",L.elem[i]); } return OK; } int main() { int i; ElemType e; SqList L; InitList(&L); for(i=1;i<=10;i++) { printf("请输入第%d个数的值:",i); scanf("%d",&e); ListInsert(&L,i,e); } printf("线性表遍历为:"); ListTraverse(L); return 0; }
浙公网安备 33010602011771号