//头文件的引入 #include #include #include //函数结果状态代码 #define TRUE 1 #define FLASE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int Status; typedef int ElemType; //定义顺序表 #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 typedef struct{ ElemType *elem; int length; int listsize; }SqList; //////// //顺序表的初始化 Status InitList_Sq(SqList &L){ L.elem = (ElemType*)malloc(sizeof(ElemType)*LIST_INIT_SIZE); if(!L.elem) exit(OVERFLOW); L.length = 0; L.listsize = LIST_INIT_SIZE; return OK; } // Status ListCreate_Sq(SqList &L, int n){ InitList_Sq(L); for(int i = 1; i <= n; ++i){ scanf("%d",&L.elem[i-1]); L.length++; } return OK; } //顺序表的插入 Status ListInsert_Sq(SqList &L, int i, ElemType e){ ElemType *newbase; ElemType *q, *p; //先进行插入范围的合理判断,如不合理错误退出 if(i < 1||i > L.length+1) return ERROR; //如果空间不够,则重新创建新空间 if(L.length >= L.listsize){ newbase = (ElemType*)realloc(L.elem, (L.listsize + LISTINCREMENT)*sizeof(ElemType)); if(!newbase) exit(OVERFLOW); L.elem = newbase; L.listsize += LISTINCREMENT; } //将i位置找到,并把地址赋值给q q = &(L.elem[i-1]); //让之后的元素后移,并给i位置赋值e for(p = &(L.elem[L.length -1 ]); p >= q; --p) *(p+1) = *p; *q = e; ++L.length; return OK; } //顺序表的删除 Status ListDelete_Sq(SqList &L, int i, ElemType &e){ ElemType *q, *p; //首先,判断删除位置是否合法 if(i < 1||i > L.length) return ERROR; p = &(L.elem[i-1]); e = *p; q = L.elem + L.length - 1; //将i后面的元素前移,表长减一 for(++p; p <= q; ++p) *(p-1) = *p; --L.length; return OK; } //顺序表查找元素位置 int ListLocate_Sq(SqList L, ElemType e){ int i,n = 0; for(i = 0; i < L.length; i++) if(L.elem[i] == e){ n = i+1; break; } return n; } //顺序表的输出 void ListPrint_Sq(SqList L){ for(int i = 1; i <= L.length; ++i){ if(i == 1) printf("%d",L.elem[i-1]); else printf(" %d",L.elem[i-1]); } printf("\n"); } int main(){ SqList L; int n, x; scanf("%d",&n); if(!ListCreate_Sq(L, n)) printf("错误"); // scanf("%d",&x); // ListInsert_Sq(L, 3, x); // ListPrint_Sq(L, n); int operationNumber; //操作次数 scanf("%d", &operationNumber); while(operationNumber != 0) { int operationType; //操作种类 scanf("%d", & operationType); if(operationType == 1) { //增加操作 int pos, elem; scanf("%d%d", &pos, &elem); ListInsert_Sq(L, pos, elem); } else if(operationType == 2) { //删除操作 int pos; ElemType elem; scanf("%d", &pos); ListDelete_Sq(L, pos, elem); printf("%d\n", elem); } else if(operationType == 3) { //查找定位操作 ElemType elem; scanf("%d", &elem); int pos = ListLocate_Sq(L, elem); if(pos >= 1 && pos <= L.length) printf("%d\n", pos); else printf("NOT FIND!\n"); } else if(operationType == 4) { //输出操作 ListPrint_Sq(L); } operationNumber--; } return 0; }
顺序表的相关操作
猜你喜欢
转载自blog.csdn.net/hackq_sxj/article/details/78244469
今日推荐
周排行