您的位置:首页 > 理论基础 > 数据结构算法

数据结构---线性表的顺序实现

2015-04-03 21:30 447 查看
写了构造空表、添加、删除、查找等操作,大部分功能都实现了 ,如果有代码写错的地方欢迎交流

//线性表顺序实现
#include <stdio.h>
#include <stdlib.h>

//线性表初始大小
#define LIST_INIT_SIZE 100

//默认数据类型为int 可修改
typedef int ElementType;

//线性表结构体
typedef struct List
{
ElementType *Base;
//表长度
int Length;
}List, *PtrList;

//建立空表
PtrList InitList()
{
PtrList L = (PtrList)malloc(sizeof(List));
L->Base = (ElementType *)malloc(LIST_INIT_SIZE * sizeof(ElementType));
L->Length = 0;
return L;
}

//在第i个元素后插入元素
int Insert(PtrList L, ElementType Elem, int i)
{
ElementType *P = L->Base;
if (L->Length > LIST_INIT_SIZE - 1)
{
printf("线性表满,插入失败\n");
return -1;
}
//插入表尾
if (i == L->Length)
*(P + L->Length) = Elem;
else if (i > L->Length || i < 0)
{
printf("插入位置有误\n");
return 0;
}
else
{
for (int j = L->Length - 1; j >= i; j--)
*(P + j + 1) = *(P + j);
*(P + i) = Elem;
}
L->Length++;
return 0;
}

//删除第i个元素
int Delete(PtrList L, int i)
{
ElementType *P = L->Base;
if (i > L->Length || i < 1)
{
printf("删除位置有误\n");
return -1;
}
//删除元素是表尾
if (i == L->Length)
{
L->Length--;
return 0;
}
else
{
for (int j = i - 1; j < L->Length; j++)
*(P + j) = *(P + j + 1);
}

L->Length--;
return 0;
}

//查找第i个元素
ElementType FindIndex(PtrList L, int i)
{
ElementType *P = L->Base;
if (i < 1 || i > L->Length)
{
printf("元素索引有误\n");
return -1;
}
return *(P + i - 1);
}

//查找元素为Elem的索引
int FindElem(PtrList L, ElementType Elem)
{
ElementType *P = L->Base;
for (int i = 0; i < L->Length; i++)
if (*(P + i) == Elem)
return i + 1;
printf("未找到元素\n");
return -1;
}

//打印线性表元素,调试用
void PrintList(PtrList L)
{
ElementType *P = L->Base;
for (int i = 0; i < L->Length; i++)
printf("%d%c", *(P + i), i == L->Length - 1 ? '\n' : ' ');
printf("表长度为: %d\n", L->Length);
}

int main()
{
PtrList L = InitList();
printf("=========================开始插入元素=========================\n");
printf("插入第一个元素后表中元素: ");
Insert(L, 1, 0);
PrintList(L);
printf("插入第二个元素后表中元素: ");
Insert(L, 2, 1);
PrintList(L);
printf("插入第三个元素后表中元素: ");
Insert(L, 4, 2);
PrintList(L);
printf("插入第四个元素后表中元素: ");
Insert(L, 3, 2);
PrintList(L);
printf("=========================结束插入元素=========================\n");
printf("=========================开始查找元素=========================\n");
printf("按值查找,查找值3的索引值: ");
printf("%d\n", FindElem(L, 3));
printf("按索引查找,查找索引1的索引值: ");
printf("%d\n", FindIndex(L, 1));
printf("=========================结束查找元素=========================\n");
printf("=========================开始删除元素=========================\n");
printf("删除索引为1的元素后表中元素: ");
Delete(L, 1);
PrintList(L);
printf("删除索引为2的元素后表中元素: ");
Delete(L, 2);
PrintList(L);
printf("=========================结束删除元素=========================\n");
system("PAUSE");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: