#include<stdio.h>
#include<stdlib.h>
#define LIST_INIT_SIZE 100 //线性表存储空间初始分配量
#define LISTINCREMNET 10//线性表存储空间的分配增量
//定义线性表结构
typedef struct {
int* elem;//存储空间基址
int length;//线性表当前长度
int Listsize;//当前分配的存储容量
}Sqlist;
//初始化
void InitList_Sq(Sqlist& L) {
L.elem = (int*)malloc(LIST_INIT_SIZE * sizeof(int));
if (!L.elem) exit(0);//存储分配失败
L.length = 0;//空表长度是0
L.Listsize = LIST_INIT_SIZE;//初始存储空间
}
//插入
void ListInsert_Sq(Sqlist& L, int i, int e) {
int* newbase;
int* p, * q;
if (i<0 || i>L.length + 1) exit(0);
if (L.length >= L.Listsize) {
newbase = (int*)realloc(L.elem, (L.Listsize+LISTINCREMNET) * sizeof(int));
if (!newbase) exit(0);//存储分配失败
L.elem = newbase;//新基址
L.Listsize += LISTINCREMNET;//增加存储容量
}
q = &(L.elem[i - 1]);
//插入操作
for (p = &(L.elem[L.length - 1]); p >= q; p--)
*(p + 1) = *p;
*q = e;
++L.length;
}
//删除
void ListDelete_Sq(Sqlist& L, int i, int& e) {
int* p, * q;
if (i<0 || i>L.length) exit(0);//i值不合法
q = &(L.elem[i - 1]);
e = *q;
p = L.elem + L.length - 1;
for (++q; q <= p; q++)
*(q - 1) = *q;
--L.length;
}
int compare(int a, int b) {//比较2个数是否相等
return a == b;
}
//在表中查找第一个值与e满足compare()的元素的位置
int LocateElem_Sq(Sqlist L, int e, int (*compare)(int, int)) {
int i = 1;
int* p = L.elem;
while (i <= L.length && !(*compare)(*p++, e))
++i;
if (i <= L.length) return i;//
else return 0;
}
//顺序表的合并
void MergeList_Sq(Sqlist La, Sqlist Lb, Sqlist& Lc) {
//la lb 的元素按值非递减排序,新表lc也是非递减顺序
int* pa, * pb, * pa_last, * pb_last, * pc;
pa = La.elem;
pb = Lb.elem;
Lc.Listsize = Lc.length = La.length + Lb.length;
pc = Lc.elem = (int*)malloc(Lc.Listsize * sizeof(int));
if (!pc) exit(0);//存储分配失败
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++;
else *pc++ = *pb++;
}
//插入剩余元素
while (pa <= pa_last) *pc++ = *pa++;
while (pb <= pb_last) *pc++ = *pb++;
}
//打印
void Listprint_sq(Sqlist& L) {
for (int i = 0; i < L.length; i++) {
printf("%d ",L.elem[i]);//打印值
printf("%d\n",&(L.elem[i]));//打印地址
}
}
//main
int main() {
Sqlist M;
int x = 0;
InitList_Sq(M);
printf("初始化完成!\n");
for (int i = 1; i <= 15; i++) {
ListInsert_Sq(M, i, i);
}
printf("线性表已建立!\n");
Listprint_sq(M);
ListDelete_Sq(M, 7, x);
Listprint_sq(M);
printf("删除的元素是:%d\n", x);
printf("%d", LocateElem_Sq(M, 10, compare));
return 0;
}
数据结构-----线性表
最新推荐文章于 2024-11-15 20:51:51 发布
本文详细探讨了线性表的基本概念、特性及其在计算机科学中的应用。内容包括线性表的定义,顺序存储和链式存储两种实现方式的优缺点,以及常见操作如插入、删除和查找的算法实现。通过实例分析,阐述了线性表在数据组织和处理中的重要角色。
摘要由CSDN通过智能技术生成