靜態(tài)數(shù)組實現(xiàn)順序線性表
/*
靜態(tài)數(shù)組實現(xiàn)順序線性表
*/
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100 //線性表存儲空間的初始分配量(靜態(tài))
#define ElemType int //線性表數(shù)據(jù)類型
#define OK 0 //操作成功執(zhí)行
#define ERROR -1 //操作失敗
#define OVERFLOW -2 //溢出
typedef int Status;
typedef struct {
ElemType data[MAXSIZE]; // 數(shù)據(jù)域
int length; //線性表當前長度
}SqList;
SqList* InitList_Sq(); //1.創(chuàng)建
Status DestroyList_Sq(SqList *L); //2.銷毀
Status ClearList_Sq(SqList *L); //3.清空
Status ListEmpty_Sq(SqList *L); //4.判空
int ListLength_Sq(SqList *L); //5.求長
ElemType GetElem_Sq(SqList *L, int i); //6.訪問元素
int LocateElem_Sq(SqList *L, ElemType e); //7.求元素位序
ElemType PriorElem_Sq(SqList *L, ElemType *cur_e); //8.求前驅
ElemType NextElem_Sq(SqList *L, ElemType *cur_e); //9.求后繼
Status ListInsert_Sq(SqList *L, int i, ElemType e); //10.插入元素
ElemType ListDelete_Sq(SqList *L, int i); //11.刪除元素
Status ListTraverse_Sq(SqList *L); //12.遍歷
SqList* InitList_Sq() //1.創(chuàng)建
{
SqList *L;
L = (SqList *)malloc(sizeof(SqList));
L->length = 0;
return L;
}
Status DestroyList_Sq(SqList *L) //2.銷毀
{
free(L);
return OK;
}
Status ClearList_Sq(SqList *L) //3.清空
{
L->length = 0;
return OK;
}
Status ListEmpty_Sq(SqList *L) //4.判空
{
if (L->length == 0)return true;
else return false;
}
int ListLength_Sq(SqList *L) //5.求長
{
return L->length;
}
ElemType GetElem_Sq(SqList *L, int i) //6.訪問元素
{
return L->data[i - 1];
}
int LocateElem_Sq(SqList *L, ElemType e) //7.求元素位序
{
for (int i = 0; i < L->length; i++)
{
if (L->data[i] == e)return (i + 1);
}
}
ElemType PriorElem_Sq(SqList *L, ElemType *cur_e) //8.求前驅
{
ElemType *p;
p = cur_e - 1;
return *p;
}
ElemType NextElem_Sq(SqList *L, ElemType *cur_e) //9.求后繼
{
ElemType *p;
p = cur_e + 1;
return *p;
}
Status ListInsert_Sq(SqList *L, int i, ElemType e) //10.插入元素
{
if (i<1 || i>L->length + 1) return ERROR;
if (L->length >= MAXSIZE) return OVERFLOW;
for (int k = L->length - 1; k >= i - 1; k--)
{
L->data[k + 1] = L->data[k];
}
L->data[i - 1] = e;
L->length++;
return OK;
}
ElemType ListDelete_Sq(SqList *L, int i) //11.刪除元素
{
if (i<1 || i>L->length + 1) return ERROR;
if (ListEmpty_Sq(L))return OVERFLOW;
ElemType e;
e = L->data[i - 1];
for (int k = i; k < L->length; k++)
{
L->data[k - 1] = L->data[k];
}
L->length--;
return e;
}
Status ListTraverse_Sq(SqList *L) //12.遍歷
{
for (int i = 0; i < L->length; i++)
{
printf("%d ", L->data[i]);
}
printf("\n");
return OK;
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。