一.线性表的基础实现(c++)
#include<iostream>
using namespace std;
#define LIST_INIT_SIZE 2
#define LISTINCREMENT 10
typedef struct {
int* datas;
int length;
int listsize;
} SqList;
// 初始化
void InitList(SqList & list){
list.datas = (int *)malloc(sizeof(int)*LIST_INIT_SIZE);
list.listsize = LIST_INIT_SIZE;
list.length = 0;
}
void display(SqList list){
for(int i=0;i<list.length;i++){
cout << list.datas[i] << " ";
}
cout << endl;
}
bool InsertList(SqList &list,int i,int ele){
if(!(i>=1 && i<=list.length+1)) return false;
if(list.length>=list.listsize){
cout << "original: ";
display(list);
list.datas = (int *)realloc(list.datas,(LISTINCREMENT + list.listsize)*sizeof(int));
list.listsize = list.listsize + LISTINCREMENT;
cout << "changed ";
display(list);
}
for(int j = list.length;j>=i;j--){
list.datas[j] = list.datas[j-1];
}
list.datas[i-1] = ele;
list.length++;
return true;
}
bool DeleteElement(SqList &L,int i){
if(!(i>=1 && i<=L.length)) return false;
for(int j=i-1;j<L.length;j++){
L.datas[j] = L.datas[j+1];
}
L.length--;
return true;
}
int FindIndex(SqList &L,int ele){
for(int i = 0;i<L.length;i++){
if(L.datas[i] == ele) return i+1;
}
return -1;
}
// c语言的main函数return必须是int!!!!
int main(){
SqList A,B,C;
InitList(A);
InitList(B);
InitList(C);
InsertList(A,1,1); InsertList(B,1,1);
InsertList(A,2,1); InsertList(B,2,1);
InsertList(A,3,3); InsertList(B,3,3);
InsertList(A,4,5); InsertList(B,4,6);
cout << "A:" << endl;
display(A);
cout << "B" << endl;
display(B);
return 0;
}
二.部分算法
合并有序序列
顺序列表A和B都是不递减的有序序列,请把他们合称为一个不递减的有序序列C
易
void MergeList(SqList A,SqList B,SqList& C){
int i=0,j=0;
int k = 1;
while(i<=A.length-1 && j<=B.length-1){
int a = A.datas[i];
int b = B.datas[j];
if(a <=b ){
InsertList(C,k,a);
i++;
}else{
InsertList(C,k,b);
j++;
}
k++;
}
cout << "i j " << i << " " << j<<endl;
while(i<=A.length-1){
InsertList(C,k,A.datas[i]);
k++;
i++;
}
while(j<=B.length-1){
InsertList(C,k,B.datas[j]);
k++;
j++;
}
}
三.知识点补充
malloc函数 && realloc函数
using namespace std;
//malloc动态分配空间
// elementType 数据类型
// n表示数据的个数
int* p = (elementType *)malloc(sizeof(elementType)*n);
//realloc 扩充和或缩小空间
//n扩充后数据的个数
//p,内存地址,该内存块之前是通过调用 malloc、calloc!!!!
int* q = (elementType *)realloc(p,sizeof(elementType)*n)
//c++实现动态分配内存
int* m = new int(n);
//new和melloc的不同?
//new使用数据的格式控制内存大小,melloc是通过申请的字节数
//用new申请的空间地址,不可以用realloc扩充!!!!