#include <stdio.h>
typedef struct{
ElementType data[MaxSize];
int length;
} SequecnedList;
// *L是指針,全稱是指針變量,是一個用來保存內存地址的變量。
//* &L是指針類型的引用,代表的是原指針,我們在函數中對指針的操作,都是對原指針的操作;
// L表示順序表指針
//創建順序表SequencedList
//*L 通過順序表指針可以操作順序表,傳遞的都是順序表指針;
//* &L 引用參數,將執行結果回傳給實參,引用符號&放在形參L的前面;輸出型參數均使用&,不論參數值是否改變;
void CreateList(SequecnedList *&L,ElementType a[],int n){
int i;
L=(SequecnedList *)malloc(sizeof(SequecnedList));
for(i=0;i<n;i++)
L->data[i]=a[i];
L->length=n;
}
//初始化
void InitList(SequecnedList* &L){
L=(SequecnedList *)malloc(sizeof(SequecnedList));
L->length=0;
}
//銷燬
void DestroyList(SequencedList *&L){
free(L);//釋放L所指向的空間
}
//判斷是否爲空表
bool ListEmpty(SequencedList *L){
return(L->length==0);
}
//求線性表的長度
int ListLength(SequecnedList *L){
return(L->length);
}
//輸出線性表
void OutputList(SequencedList *L){
int i;
if(ListEmpty(L)) return;
for(i=0;i<L->length;i++){
printf("%c",L->data[i]);
}
printf("\n");
}
//求某個數據元素值
//返回第i個元素的值,存放在e中
//此算法時間複雜度爲O(1)
bool GetItem(SequencedList *L,int i,ElementType &e){
if(i<0||i>L->length) return false;
e=L->data[i-1];
return true;
}
//按元素值查找
//順序查找第一個與e相等的元素邏輯位序,若不存在返回0
int LocateElem(SequencedList *L,ElementType e){
int i=0;
while(i<L->length&&L->data[i]!=e){
i++;
}
if(i>=L->length) return 0;
else return i+1;
}
//插入元素
//O(n)
bool ListInsert(SequencedList *&L,ElementType e,int i){
int j;
if(i<0||i>L->length+1) return false;
for(j=L->length;j>i;j--){
L->data[j]=L->data[j-1];//將data[i......n-1]往後移動一個位置
}
L->data[i]=e;//插入元素e
L->length++;//順序表長度增長1
return true;
}
//刪除元素
//O(n)
bool ListDelete(SequencedList *&L,ElementType e,int i){
int j;
if(i<0||i>L->length+1) return false;
i--; //將順序表邏輯符號轉化爲物理符號
e=L->data[i];
for(j=i;j<L->length-1;j++){
L->data[j]=L->data[1+i];
}
L->length--;
return true;
}
//設順序表L有10個整數。設計一個算法,以第一個元素爲基準,
//將所有小於等於他的元素放到該元素的前面,所有大於他的元素放在該元素的後面
void Moving(Sqlist *&L){
int jizhun=L->data[0];
int i=0;
int j=L->data[L->length-1];
while(i<j){
while(L->data[i]<=jizhun){
i++;
}
L->data[j]=L->data[i];
while(L->data[j]>jizhun){
j--;
}
L->data[i]=L->data[j];
}
L->data[i]=jizhun;
}