1 #include <iostream> 2 3 using namespace std; 4 //顺序链表 5 #define MAXSIZE 20 6 #define OK 1 7 #define ERROR 0 8 #define TRUE 1 9 #define FALSE 0 10 typedef int ElemType; 11 typedef int Status; 12 typedef struct 13 { 14 ElemType data[MAXSIZE]; 15 int length; 16 }SqList; 17 18 //初始化 19 void InitSqlist(SqList *L){ 20 L->length=0; 21 } 22 //获取长度 23 Status GetLength(SqList L){ 24 return L.length; 25 } 26 //获取操作 27 Status GetElem(SqList L, int i, ElemType *e){ 28 if(L.length==0 || i<1 || i>L.length) 29 return ERROR; 30 *e = L.data[i-1]; 31 return OK; 32 } 33 //插入操作 34 Status ListInsert(SqList *L, int i, ElemType e){ 35 int k; 36 if(L->length == MAXSIZE) 37 return ERROR; 38 if(i<1 || i>L->length+1) 39 return ERROR; 40 if(i<=L->length){ 41 for(k=L->length-1; k>=i-1; k--){ 42 L->data[k+1]=L->data[k]; 43 } 44 } 45 L->data[i-1]=e; 46 L->length++; 47 return OK; 48 } 49 //删除操作 50 Status ListDelete(SqList *L, int i, ElemType *e){ 51 int k; 52 if(L->length == 0) 53 return ERROR; 54 if(i<1 || i>L->length) 55 return ERROR; 56 *e=L->data[i-1]; 57 if(i<L->length){ 58 for(k=i; k<L->length; k++){ 59 L->data[k-1]=L->data[k]; 60 } 61 } 62 L->length--; 63 return OK; 64 65 } 66 int main() 67 { 68 SqList myList; 69 int del=0, get=0; 70 int pos; 71 InitSqlist(&myList); 72 for(int i=1; i<=10; i++){ 73 if(ListInsert(&myList, i, i)==OK) 74 cout << "insert:" << i << endl; 75 } 76 cout <<"输入删除位置:"<<endl; 77 cin >> pos; 78 if(ListDelete(&myList, pos, &del)==OK) 79 cout << "Delete:" << del << endl; 80 cout << "All Elem:"<<endl; 81 for(int i=1; i<=GetLength(myList); i++){ 82 if(GetElem(myList, i, &get)==OK) 83 cout << get << ‘ ‘; 84 } 85 86 return 0; 87 }
时间: 2024-10-08 20:22:00