【线性表】线性表的顺序存储结构
代码
#include <iostream>
#include <cstdio>
using namespace std;
#define OK 1
#define ERROR 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int status;
typedef int ElemType;
typedef struct {
ElemType *elem;
int length;
int listsize;
}SqList;
status InitList_Sq(SqList &L){
L.elem = (ElemType * )malloc(LIST_INIT_SIZE * sizeof(ElemType));
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return OK;
}
status ListInsert_Sq(SqList &L, int i, ElemType e){
if (i < 1 || i > L.length + 1) return ERROR;
if (L.length >= L.listsize){
ElemType * newbase = (ElemType * )realloc(L.elem, (LIST_INIT_SIZE + LISTINCREMENT) * sizeof(ElemType));
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
ElemType * q = &(L.elem[i-1]);
for (ElemType * 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){
if (i < 1 || i > L.length) return ERROR;
ElemType * p = &(L.elem[i-1]);
e = *p;
ElemType * q = L.elem + L.length - 1;
for (++p; p <= q; p++) *(p-1) = *p;
--L.length;
return OK;
}
int LocateElem_Sq(SqList L, ElemType e){
for (int i = 0; i < L.length; i++){
if (L.elem[i] == e) return (i+1);
}
return 0;
}
void MergeList_Sq(SqList La, SqList Lb, SqList &Lc){
ElemType * pa = La.elem;
ElemType * pb = Lb.elem;
Lc.listsize = Lc.length = La.length + Lb.length;
ElemType * pc = Lc.elem = (ElemType * )malloc(Lc.listsize * sizeof(ElemType));
ElemType * pa_last = La.elem + La.length - 1;
ElemType * pb_last = Lb.elem + Lb.length - 1;
while (pa <= pa_last && pb <= pb_last){
if (*pa <= *pb) *pc++ = *pa++;
else *pc++ = *pb++;
}
while (pa <= pa_last) *pc++ = *pa++;
while (pb <= pb_last) *pc++ = *pb++;
}
int main(){
SqList La, Lb, Lc;
InitList_Sq(La);
InitList_Sq(Lb);
InitList_Sq(Lc);
int n;
printf("请输入第一个顺序线性表数据数量:\n");
scanf("%d", &n);
printf("请输入第一个顺序线性表数据:\n");
for (int i = 0; i < n; i++){
scanf("%d", &La.elem[i]);
La.length++;
}
printf("请输入第二个顺序线性表数据数量:\n");
scanf("%d", &n);
printf("请输入第二个顺序线性表数据:\n");
for (int i = 0; i < n; i++){
scanf("%d", &Lb.elem[i]);
Lb.length++;
}
return 0;
}