順序表--C語言
阿新 • • 發佈:2018-11-12
順序表結構如上
#include <stdbool.h> typedef int Position; typedef int ElementType; #define MAXSIZE 1000 typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; }; //初始化 List MakeEmpty() { List L; L = (List)malloc(sizeof(struct LNode)); L->Last = -1; return L; } #define ERROR -1 Position Find(List L, ElementType X) { Position i = 0; while (i <= L->Last&&L->Data[i] != X) i++; if (i > L->Last) return ERROR; else return i; //找到後返回儲存位置 } bool Insert(List L, ElementType X, Position P) { //在L的指定位置P前插入一個新元素X Position i; if (L->Last == MAXSIZE - 1) { printf("表滿"); return false; } if (P<0 || P>L->Last + 1) { //檢查插入位置合法性 printf("位置不合法"); return false; } for (i = L->Last; i >= P; i--) L->Data[i + 1] = L->Data[i]; //將位置P及以後的元素順序向後移動 L->Data[P] = X; L->Last++; return true; } bool Delete(List L, Position P) { //從L中刪除指定位置P的元素 Position i; if (P<0 || P>L->Last) { printf("位置%d不存在元素", P); return false; } for (i = P + 1; i <= L->Last; i++) L->Data[i-1] = L->Data[i]; L->Last--; return true; }