資料結構實驗一:(1)(順序表)線性表的各種操作SqList
#include<iostream> #include<malloc.h> #include<cstdio> #define MAXSIZE 10 using namespace std; //typedef struct SqList *L; typedef struct{ char data[MAXSIZE]; int length; }SqList;
void InitList(SqList *&L){ L=(SqList *)malloc(sizeof(SqList)); L->length=0; }
bool InsertList(SqList *&L,int i,char e){ int j; if(i<1||i>L->length+1) return false; i--; for(j=L->length;j>i;j--) L->data[j]=L->data[j-1]; L->data[i]=e; L->length++; return true; }
bool DeleteList(SqList *&L,int i,char e){ int j; if(i<1||i>L->length) return false; i--; e=L->data[i]; for(j=i;j<L->length-1;j++) L->data[j]=L->data[j+1]; L->length--; return true; }
int DispList(SqList * L){ int i; for(i=0;i<L->length;i++) printf("%c ",L->data[i]); printf("\n"); }
int LengthList(SqList * L){ return (L->length); }
bool ListEmpty(SqList * L){ return (L->length==0); }
void DestroyList(SqList *& L){ free(L); }
int main(){
SqList *L; char e; int i; InitList(L); InsertList(L,1,'a'); InsertList(L,2,'b'); InsertList(L,3,'c'); InsertList(L,4,'d'); InsertList(L,5,'e'); DispList(L); printf("%d",LengthList(L)); printf("\n"); if(ListEmpty(L)=='true') printf("yes"); else printf("no"); printf("\n"); printf("%c",L->data[2]); printf("\n"); for(i=0;i<L->length;i++) if(L->data[i]=='a') printf("%d",i+1); printf("\n"); InsertList(L,4,'f'); DispList(L); DeleteList(L,3,e); DispList(L); DestroyList(L);
return 0; }
總結:
1.線性表順序儲存型別可以描述如下:
typedef struct
{
ElemType data[MaxSize];
int length;
}SqList; 假設ElemType 是int 類,使用如下自定義型別語句:‘
typedef int ElemType;
2。線性表的九種基本運算:
void InitList(SqList *&L)
void DestroyList(SqList *&L)
bool ListEmpty(SqList *L) int ListLength(SqList *L)
void DispList(SqList *L)
bool GetElem(SqList *L,int i,ElemType &e)
int LocateElem(SqList*L,ElemType e)
bool ListInsert(SqLsit *L,int i,ElemType e)
bool ListDelete(SqList *&L,int i,ElemType &e)
總共返回得到的元素和刪除元素需要返回元素e的地址
3.注意
void initlist(sqlist *&L);意思是說,引數L是sqlist型別,且引數是以別名傳參出現的。所謂別名的意思說就是,在這個函式中,函式可以修改L的修,且只能在c++中使用。