您的位置:首页 > 编程语言 > C语言/C++

顺序表(C语言)

2015-08-06 10:17 435 查看
#include <stdio.h>
#include <stdlib.h>

#define maxsize 3
#define addsize 2

typedef int elemType;

typedef struct
{
elemType *List;//首地址
int length;//长度
int listSize;//分配的内存大小
} sqList;

//初始化顺序链表
void initList(sqList *L)
{

L->List=(elemType *)malloc(maxsize*sizeof(elemType));
if(!L->List)
exit(1);
L->length=0;
L->listSize=maxsize;
}

//空间不够重新分配内存
void reaList(sqList *L)
{
L->List=(elemType *)realloc(L->List,(L->listSize+addsize)*sizeof(elemType));
if(!L->List)
exit(1);
L->listSize=L->listSize+addsize;
}

//添加元素
void appendList(sqList *L,elemType elem)
{
if(L->length==L->listSize)
reaList(L);
L->List[L->length]=elem;
L->length++;
}

//插入元素
void insertList(sqList *L,elemType elem,int pos)
{
if(L->length==L->listSize)
reaList(L);
int i;
for(i=L->length;i>pos-1;i--)
L->List[i]=L->List[i-1];
L->List[i]=elem;
L->length++;
}

//移除元素
elemType moveList(sqList *L,int pos)
{
if(pos<0||pos>L->length)
exit(1);
elemType temp=L->List[pos-1];
int i;
for(i=pos-1;i<L->length-1;i++)
L->List[i]=L->List[i+1];
L->length--;
return temp;
}

//遍历顺序表
void displayList(sqList *L)
{
int i;
for(i=0;i<L->length;i++)
printf("%d\t",L->List[i]);
printf("\r\n");
}

//返回顺序表元素个数
int lengthList(sqList *L)
{
return L->length;
}

//判断顺序表是否为空
bool isEmptyList(sqList *L)
{
return L->length==0;
}

//查找元素
int searchList(sqList *L,elemType elem)
{
int i;
if(!isEmptyList(L))
for(i=0;i<L->length;i++)
if(L->List[i]==elem)
return i+1;
printf("找不到该元素\r\n");
return -1;
}

int main()
{
sqList L;
initList(&L);
appendList(&L,1);
appendList(&L,2);
insertList(&L,6,2);
appendList(&L,3);
//displayList(&L);
appendList(&L,1);
insertList(&L,6,4);
displayList(&L);
elemType temp=moveList(&L,4);
printf("移除:%d\t\t",temp);
displayList(&L);
temp=searchList(&L,3);
if(temp!=-1)
printf("查找的元素位置为:%d\r\n",temp);
temp=searchList(&L,4);
if(temp!=-1)
printf("查找的元素位置为:%d\r\n",temp);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息