typedefs.h:
- #define OK 1
- #define ERROR 0
- #define INFEASIBLE -1
- #define OVERFLOW -2
- typedef int Status;
- typedef enum
- {
- FALSE,
- TRUE
- }BOOL;
顺序表定义:
- #include "stdio.h"
- #define TRUE 1
- #define FALSE 0
- #define OK 1
- #define ERROR 0
- #define INFEASIBLE -1
- #define OVERFLOW -2
- #define LIST_INIT_SIZE 100
- #define LISTINCREMENT 10
- typedef int Status;
- typedef int ElemType;
- typedef struct{
- ElemType *elem;
- int length;
- int listsize;
- }SqList;
- /*初始化线性表*/
- Status InitList_Sq(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 ListInsert_Sq(SqList *L,int i,ElemType e){
- ElemType *q,*p,*newbase;
- if (i<1||i>L->length+1) return ERROR; /*i范围[1,n+1 ]*/
- if (L->length>=L->listsize){
- /*重新申请空间*/
- newbase=(ElemType*)realloc(L->elem,(L->listsize+LISTINCREMENT)*sizeof(ElemType));
- if (!newbase)
- exit(OVERFLOW);
- L->elem=newbase;
- L->listsize+=LISTINCREMENT;
- }
- q=&(L->elem[i-1]);
- /*后移第i到n个元素*/
- for(p=&(L->elem[L->length-1]);p>=q;--p)
- *(p+1)=*p;
- *q=e;
- ++L->length;
- return OK;
- }
- /*删除元素*/
- Status ListDelete_Sq(SqList *L,int i,ElemType *e){
- ElemType *p,*q;
- 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;
- }
- /*清空线性表*/
- void ClearList_Sq(SqList *L)
- {
- L->length=0;
- }
- /*线性表判空*/
- BOOL ListEmpty_Sq(SqList *L)
- {
- return L->length==0?TRUE:FALSE;
- }
- /*返回线性表长度*/
- int ListLength(SqList *L)
- {
- return L->length;
- }
- /*获取线性表第i个元素*/
- Status GetElem_Sq(SqList *L,int i,ElemType *elem)
- {
- if(i<1 || i>L->length)
- return OVERFLOW;
- *elem=L->elem[i-1];
- return OK;
- }
- int main(int argc,char* argv[]){
- SqList Lst;
- int i,n=10;
- ElemType e;
- if (InitList_Sq(&Lst)==OK){
- for(i=1;i<=n;i++)
- if(ListInsert_Sq(&Lst,i,(ElemType)i)!=OK) break;
- printf("\n");
- for (i=0;i<Lst.length;i++)
- printf("i,e=%d,%d\n",i,Lst.elem[i]);
- getch();
- if (ListDelete_Sq(&Lst,5,&e)==OK){
- printf("delete_elem=%d\n",(int)e);
- getch();
- for (i=0;i<Lst.length;i++)
- printf("i,e=%d,%d\n",i,Lst.elem[i]);
- }
- }
- getch();
- return 0;
- }