#include<stdio.h> #include<stdlib.h> #include<malloc.h> #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 #define OVERFLOW -2 #define ERROR 0 #define OK 1 using namespace std; //typedef int Status; typedef struct { int *elem; //指向整个线性表的基址 int length; //当前长度 int listsize; //总容量(以sizeof(ElemType)为单位) }SqList; int InitList_Sq(SqList &L) //构建有序表 { L.elem = NULL; L.elem = (int *)malloc(LIST_INIT_SIZE * sizeof(int)); //给表申请动态空间,最多存100个整形数据 if(!L.elem) exit(OVERFLOW); //申请失败 L.length = 0; L.listsize = LIST_INIT_SIZE; return OK; } int ListInsret_Sq(SqList &L,int i,int e) //在第i个位置插入元素e { if(i < 1 || i > L.length + 1) return ERROR; if(L.length >= L.listsize) { //更改内存大小,新的大小一定要大于原来的大小,不然的话会导致数据丢失 int *newbase = (int *)realloc(L.elem,(L.listsize + LISTINCREMENT)*sizeof(int)); if(!newbase) exit(OVERFLOW); L.elem = newbase; L.listsize += LISTINCREMENT; } int *q = &(L.elem[i - 1]); //申请的elem是一连串的。这里不好懂。 for(int *p = &(L.elem[L.length - 1]);p >= q;--p) *(p + 1) = *p; *q = e; ++L.length; return OK; } int ListDelete_Sq(SqList &L,int i,int &e) //删除第i个元素,而且返回e的值 { if(i < 1 || i > L.length) return ERROR; int *p = &(L.elem[i - 1]); //p为第i个元素的地址 e = *p; int *q = L.elem + L.length - 1; //q为最后一个元素的地址 for(++p;p <= q;++p) *(p - 1) = *p; --L.length; return OK; } int ListSearch_Sq(SqList &L,int e,int &i) { int temp = 0,flag = 1; int *p,*q = &(L.elem[L.length - 1]); for(p = &L.elem[0];p <= q;p ++) { temp++; if(*p == e) { i = temp; flag = 1; } } if(!flag) return ERROR; else return OK; } int main() { // freopen("out.txt","w",stdout); SqList a,b; InitList_Sq(a); InitList_Sq(b); ListInsret_Sq(a,1,1); ListInsret_Sq(a,2,2); ListInsret_Sq(a,3,3); ListInsret_Sq(a,4,4); ListInsret_Sq(a,5,5); ListInsret_Sq(a,6,6); ListInsret_Sq(a,7,7); ListInsret_Sq(a,8,8); ListInsret_Sq(a,9,9); ListInsret_Sq(b,1,4); ListInsret_Sq(b,2,5); ListInsret_Sq(b,3,6); ListInsret_Sq(b,4,7); ListInsret_Sq(b,5,8); ListInsret_Sq(b,6,9); int i; ListDelete_Sq(a,3,i); printf("您删除了:%d ",i); ListSearch_Sq(a,4,i); printf("这个元素在第%d个位置 ",i); return 0; }
版权声明:本文博主原创文章,博客,未经同意不得转载。