线性表的基本操作

以下是线性表顺序存储的一些基本操作:

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>


#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10


int OK = 1;
int ERROR = -1;
int OVERFLOW = -1;


typedef struct {
int *elem; //存储空间基址 
int length; //当前长度 
int listsize; //链表长度 
}SqList;


int InitList_Sq(SqList &L) {
L.elem = (int *)malloc(LIST_INIT_SIZE*sizeof(int));
if(!L.elem) exit(OVERFLOW);
L.length = 0;
L.listsize = LIST_INIT_SIZE;

return OK;
} //InitList Sq


int InsertInto_Sq(SqList &L, int location, int e) {
//i值是否合法
//存储空间是否满足
int *newbase;
if(location<1 || location > L.length+1) return ERROR;
if(L.length >= L.listsize) {
newbase = (int *)realloc(L.elem,LIST_INIT_SIZE+LISTINCREMENT*sizeof(int)); //新的存储空间分配失败 
if(!newbase) exit(OVERFLOW);
L.elem = newbase;
L.listsize += LISTINCREMENT;
}

int *q,*p; 
q = &L.elem[location-1];
for(p = &(L.elem[L.length-1]); p>=q; --p) { //从表尾开始移动 
*(p+1) = *p;
}
*q = e;
++L.length;

return OK;
}//InsertList Sq


int Delete_Sq(SqList &L, int location) {
if(location<1 || location>L.length) return ERROR;

int *q,*p;
q = &(L.elem[location-1]);
p = L.elem + L.length-1;
for(++q; q <= p; ++q) { //不可以q<p,可以q<p+1
*(q-1) = *q;
}


--L.length;
return OK;
}//DeleteList Sq


int LocateElem_Sq(SqList &L, int e) {
int *q,*p;

q = &(L.elem[0]);
p = L.elem+L.length;
for(; q<p; ++q) {
if(*q==e) return 1;
}

return 0;
}


void MargeList_Sq(SqList La, SqList Lb, SqList &Lc) { //两个链表的合并 
int *pa, *pa_last, *pb, *pb_last, *pc, *pc_last;

pa = La.elem;
pb = Lb.elem;

Lc.listsize = Lc.length = La.length + Lb.length;

pc = Lc.elem =(int *)malloc(Lc.listsize*sizeof(int));
if(!Lc.elem) exit(OVERFLOW);

pa_last = La.elem + La.length-1;
pb_last = Lb.elem + Lb.length-1;

while(pa <= pa_last || pb <= pb_last) {
if(*pa <= *pb) *pc++ = *pa++;         //等价于等价于 *pc=*pa; pc++; pa++;  
else *pc++ = *pb++; 
}

while(pa <= pa_last) *pc++ = *pa++;
while(pb <= pb_last) *pc++ = *pb++;
}//MergeList_Sq




int main() {
SqList list;
InitList_Sq(list);
InsertInto_Sq(list, 1, 1);
InsertInto_Sq(list, 2, 3);
InsertInto_Sq(list, 3, 5);
InsertInto_Sq(list, 4, 7);
for(int i = 0; i<list.length ;i++) {
printf("%d\n", list.elem[i]);
}
printf("\n");
Delete_Sq(list, 1);
for(int i = 0; i<list.length ;i++) {
printf("%d\n", list.elem[i]);
}
printf("\n");
int a = LocateElem_Sq(list, 3);
printf("%d", a);
}

今天开始考研数据结构的复习,希望自己能坚持,坚持才有进步,你想要的都会有的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值