// 顺序表实现
#include <stdio.h>
#include "windows.h"
#include "stdlib.h"
#define MaxSize 50
#define ElemType int
// 定义顺序表结构体
typedef struct SeqList
{
ElemType data[MaxSize];
int length;
} SeqList;
// 初始化顺序表
void InitSeqList(SeqList *L)
{
L->length = 0;
}
//建立顺序表
boolean createList(SeqList *L, int size)
{
if (size > MaxSize)
{
printf("空间不足无法创建\n");
return FALSE;
}
// 为顺序表赋值
for (int k = 0; k < size; k++)
{
L->data[k] = k + 1;
}
// 顺序表长度
L->length = size;
return TRUE;
}
// 判空操作
boolean Empty(SeqList *L)
{
if (L->length != 0)
{
return FALSE;
}
return TRUE;
}
// 查询顺序表长度
int Length(SeqList *L)
{
return L->length;
}
void PrintList(SeqList *L)
{
for (int i = 0; i < L->length; i++)
printf("%d ", (L->data[i]));
}
// 前插法
boolean Insert(SeqList *L, int index, int ele)
{
if (L->length > MaxSize)
{
printf("数组上溢,无法插入");
return FALSE;
}
if (index < 1 || index > L->length)
{
printf("插入位置不合法");
return FALSE;
}
for (int i = L->length; i >= index; i--)
{
// 向后偏移一个位置
L->data[i] = L->data[i - 1];
}
L->data[index - 1] = ele;
// 链表长度加一
L->length = L->length + 1;
return TRUE;
}
//按位置删除元素
boolean RemoveIndex(SeqList *L, int index)
{
if (index < 1 || index > MaxSize)
return FALSE;
int i;
for (i = index; i < L->length; i++)
{
L->data[i - 1] = L->data[i];
}
L->length = L->length - 1;
return TRUE;
}
// 按值删除元素
boolean RemoveVal(SeqList *L, int value)
{
int i;
for (i = 0; i < L->length; i++)
{
if (L->data[i] == value)
for (int j = i; j < L->length; j++)
{
L->data[j] = L->data[j + 1];
}
}
L->length -= 1;
return TRUE;
}
// 按值查找元素
int findVal(const SeqList *L, int value)
{
int i = 0;
for (i = 0; i < L->length; i++)
{
if (L->data[i] == value)
return i + 1;
}
return 0;
}
int main()
{
SeqList list1;
InitSeqList(&list1); //初始化顺序表
if (Empty(&list1))
{
printf("初始化顺序表成功!\n");
}
createList(&list1, 5); //建立一个长度为5的线性表
Insert(&list1, 3, 100);
// RemoveIndex(&list1, 3);
RemoveVal(&list1, 100);
printf("%d\n", findVal(&list1, 100));
PrintList(&list1);
return 0;
}
C语言数据结构之实现顺序表
最新推荐文章于 2024-07-18 13:20:33 发布