The Sqlist for Linear table | Data
The Code in Data book (5th Edition) from the 35 page to 37 page
#define MaxSize 50
typedef int ElemType;
//Sqlist structure
typedef struct{
ElemType data[MaxSize]; //save Sqlist elements
int length; //save Sqlist length
} SqList;
//Create Sqlist
void CreateList(SqList *&L, ElemType a[], int n) {
L = (SqList *) malloc(sizeof(SqList));
for ( int i = 0; i < n; i++ )
L->data[i] = a[i];
L->length = n;
}
//Initialization Sqlist
void InitList(SqList * &L){
L = (SqList *)malloc(sizeof(SqList));//Allocate space for Sqlist
L->length = 0;//Make empty linear table length 0
}
//Destroyed Sqlist
void DestroyList(SqList *&L) {
free(L);
}
//Determine if a Sqlist is empty
bool ListEmpty(SqList *L) {
return (L -> length == 0);
}
//Find the length of Sqlist
int ListLength(SqList *L) {
return(L->length);
}
//Output Sqlist
void DispList(SqList *L) {
for (int i = 0; i < L->length; i++)//Scan Sqlist outputs values for each element
printf("%d ", L->data[i]);
printf("\n");
}
//Find the value of a data element in the Sqlist
bool GetElem(SqList *L, int i, ElemType &e) {
if ( i < 1 || i > L->length )
return false; //When parameters i error return false
e = L->data[i - 1]; //Get elements value
return true; //When find elements success return true
}
//When position elements e success on Sqlist, find in order of elements values
int LocateElem(SqList *L, ElemType e) {
int i = 0;
while (i < L-> length && L->data[i] != e)
i++; //Find elements e
if (i >= L->length) //Return 0 when not found
return 0;
else
return i + 1; //return logical sequence number when found
}
//Insert data elements
bool ListInsert(SqList *&L, int i, ElemType e) {
int j;
if (i<1 || i > L->length + 1)
return false;//Return false when wrong parameters i
i--;//Corvert Sqlist logical serical numbers to physical serial numbers
for (j = L->length; j > i; j--) //Move the data[i] and rear all elements back one position
L->data[j] = L->data[j - 1];
L->data[i] = e;//Insert elements e
L->length++;//Sqlist length add 1
return true;
}
//Delete data elements
bool ListDelete(SqList *&L, int i, ElemType &e) {
int j;
if (i<1 || i > L->length)
return false;//return false when wrong paraments
i--; //Convert sequential table logical serial numbers to physical serial numbers
e = L->data[i];
for (j = i; j < L->length - 1; j++) //Move the data[i] and rear all elements forward one position
L->data[j] = L->data[j + 1];
L->length--;//Sqlist length minus 1
return true;//return true success;
}
By Homework 1
如有侵权,请联系作者删除