#include <stdio.h>
#define MaxSize 50 typedef int ElemType;
typedef struct { ElemType data[MaxSize]; int len; } SqList;
bool ListInsert(SqList &L, int i, ElemType e) {
if (i < 1 || i > L.len + 1) { return false; }
if (L.len > MaxSize) { return false; }
for (int j = L.len; j >= i; j--) { L.data[j] = L.data[j - 1]; } L.data[i - 1] = e; L.len++; return true; }
void PrintSqlist(SqList L) { int i; for (i = 0; i < L.len; i++) { printf("%3d", L.data[i]); } printf("\n"); }
bool ListDelete(SqList &L, int i, ElemType &del) {
if (i < 1 || i > L.len) { return false; }
del = L.data[i - 1]; for (int j = i; j < L.len; j++) { L.data[j - 1] = L.data[j]; } L.len--; return true; }
int LocateElem(SqList L, ElemType e) { int i; for (i = 0; i < L.len; i++) { if (e == L.data[i]) { return i + 1; } } return 0; }
int main() { SqList L; bool ret; L.data[0] = 1; L.data[1] = 2; L.data[2] = 3; L.len = 3; ret = ListInsert(L, 2, 8); if (ret) { printf("Insert sqlist success!\n"); PrintSqlist(L); } else { printf("Insert sqlist defalse!\n"); } printf("----------------------\n"); ElemType del; ret = ListDelete(L, 3, del); if (ret) { printf("Delete sqlist success!\n"); printf("del element = %d\n", del); PrintSqlist(L); } else { printf("Delete sqlist defalse!\n"); } printf("----------------------\n"); int pos; pos = LocateElem(L, 8); if (pos) { printf("success find this element!\n"); printf("find pos=%d\n", pos); } else { printf("Don't find this element!\n"); } return 0; }
|