/*
Date: 28/04/19 19:01
Description: 顺序表基本操作
*/
#include<stdio.h>
#include<stdlib.h>
#define LIST_INIT_SIZE 5
#define INCREMENT 10 //自动增长因子
typedef int ElemType;
typedef int Status;
typedef struct //定义数据类型
{
ElemType *pbase; //pbase指向线性表起始指针,即第一个元素的首地址
int listsize; //线性表总长度
int length; //线性表当前长度
}SqList;
void InitList(SqList *L);
void CreateList(SqList *L,ElemType a[],int n) ;
void ShowList(SqList *L);
Status InsertList(SqList *L,int i,ElemType e);
Status DeleteList(SqList *L,int i);
void AppendList(SqList *L,ElemType e);
void InvertList(SqList *L);
int main()
{
printf("初始化线性表\n");
SqList L;
InitList(&L);
ElemType a[] = {1,2,3,4,5};
CreateList(&L,a,5);
ShowList(&L);
printf("创建的线性表长度为:%d\n",L.length);
printf("插入元素\n");
InsertList(&L,2,10);
ShowList(&L);
printf("删除元素\n");
DeleteList(&L,4);
ShowList(&L);
ElemType e;
printf("追加元素:");
scanf("%d",&e);
AppendList(&L,e);
ShowList(&L);
InvertList(&L);
ShowList(&L);
return 0;
}
/*
初始化线性表,使得pbase指向数组首元素
*/
void InitList(SqList *L)
{
L->listsize = LIST_INIT_SIZE;
L->pbase = (ElemType*)malloc(L->listsize*sizeof(ElemType)); //为线性表分配内存
if (!L->pbase) //分配失败
{
printf("malloc fail\n");
exit(0);
}
L->length = 0; //默认长度0
}
/*
创建线性表
*/
void CreateList(SqList *L,ElemType a[],int n)
{
int i = 0;
for (i;i<n;i++)
{
L->pbase[i] = a[i];
}
L->length = n;
}
void ShowList(SqList *L)
{
int i = 0;
while (i<L->length)
{
printf("pbase[%d]=%d ",i,L->pbase[i]);
i++;
}
printf("\n");
}
/*
插入一个元素
*/
Status InsertList(SqList *L,int i,ElemType e) //i的值从1开始,
{
if (i<1 || i >L->length+1) //位置不正确 1<=i<=length+1
{
printf("位置输入错误\n");
return 0;
}
if (L->length == L->listsize) //空间已满
{
printf("空间已满\n");
L->pbase = (ElemType*)realloc(L->pbase,(L->listsize+INCREMENT)*sizeof(ElemType)); // 为线性表重新分配内存
L->listsize = L->listsize + INCREMENT;
printf("%d\n",L->listsize);
}
for (int j = L->length;j>=i;j--) //从最后一个元素开始往后移动一个元素
{
L->pbase[j] = L->pbase[j-1];
}
L->pbase[i-1] = e;
L->length ++;
return 1;
}
/*
追加元素
*/
void AppendList(SqList *L,ElemType e)
{
if (L->length == L->listsize)
{
L->pbase = (ElemType *)realloc(L->pbase,(sizeof(ElemType)*(L->listsize+INCREMENT)));
L->listsize = L->listsize + INCREMENT;
printf("分配内存成功%d\n",L->listsize);
}
L->pbase[L->length] = e;
L->length++;
}
/*
删除一个元素
*/
Status DeleteList(SqList *L,int i)
{
if (L->length == 0)
{
return 0;
}
if (i<1 || i>L->length)
{
return 0;
}
for (int j = i;j<L->length;j++) //元素向前移
{
L->pbase[j-1] = L->pbase[j];
}
L->length --;
return 1;
}
/*
倒置
*/
void InvertList(SqList *L)
{
// int i = ((L->length)+1)/2;
// ElemType temp;
// for (int j = 0;j<i;j++)
// {
// temp = L->pbase[j];
// L->pbase[j] = L->pbase[L->length-1-j];
// L->pbase[L->length-1-j] = temp;
// }
int i = 0; //定义两个变量 一个从头开始加,一个从最后开始减
int j = L->length-1;
ElemType temp;
while (i<j)
{
temp = L->pbase[i];
L->pbase[i] = L->pbase[j];
L->pbase[j] = temp;
i++;
j--;
}
}
顺序表的基本操作
最新推荐文章于 2024-01-23 10:50:51 发布