顺序表的实现
声明:
#include <stdio.h>
#include "stdlib.h"
typedef int DataType;
1.构造一个机构体
//创建空顺序表
PSeqList createNullList_seq(int m)
{
PSeqList palist=(PSeqList)malloc(sizeof(struct SeqList));
if (palist!=NULL)
{
palist->element=(DataType *)malloc(sizeof(DataType) * m);
if(palist->element)
{
palist->MAXNUM=m;
palist->n=0;
return palist;
}
else
{
free(palist);
}
}
printf("out of space!! \n");
return NULL;
}
2.
//判断palist所指顺序表是不是为空表
int isNullList_Seq(PSeqList palist)
{
return (palist->n==0);
}
3.
//在palist所指顺序表中寻找第一个值为X的元素下标
int locate_seq(PSeqList palist,DataType x)
{
int q;
for(q=0;q<palist->n;q++)
{
if (palist->element[q]==x) {
return q;
}
}
return -1;
}
4.
//顺序表的插入,在palist所指顺序表中下标为p的元素之前插入元素x
int insertPre_seq(PSeqList palist,int p,DataType x)
{
DataType * pos1;
int q;
if(palist->n>=palist->MAXNUM)
{
//顺序表空间的扩展 www.zzzyk.com
pos1=(DataType*)malloc(sizeof(DataType)*palist->MAXNUM*2);
if(pos1==NULL)
{
printf("Overflow!");
return 0;
}
for(q=0;q<palist->MAXNUM;q++)
{
pos1[q]=palist->element[q];
}
free(palist->element);
palist->element=pos1;
palist->MAXNUM*=2;
}
if (p<0||p>palist->n) {
printf("Not Exist!! \n");
return 0;
}
for(q=palist->n-1;q>=p;q--)
{
palist->element[q+1]=palist->element[q];
}
palist->element[p]=x;
palist->n=palist->n+1;
return 1;
}
5.
//顺序表的插入,在palist所指顺序表中下标为p的元素之后插入元素x
int insertPost_seq(PSeqList palist,int p,DataType x)
{
int q;
if(palist->n>=palist->MAXNUM)
{
printf("OverFlow \n");
return 0;
}
if (p<0||p>palist->n) {
printf("Not Exist!! \n");
return 0;
}
for(q=palist->n-1;q>=p+1;q--)
{
palist->element[q+1]=palist->element[q];
}
palist->element[p+1]=x;
palist->n=palist->n+1;
return 1;
}
6.
//顺序表的删除,在palist所指顺序表中删除下标为p的元素
int deleteP_seq(PSeqList palist,int p)
{
int q;
if (q<0||q>palist->n-1)
{
printf("Not Exist!! \n");
return 0;
}
for(q=p;q<palist->n-1;q++)
{
palist->element[q]=palist->element[q+1];
}
palist->n=palist->n-1;
return 1;
}
7.
int deleteV_seq(PSeqList palist,DataType x)
{
int q=locate_seq(palist,x);
deleteP_seq(palist,q);
return 1;
}
8.
测试
int main()
{
int i;
PSeqList list1= createNullList_seq(50);
insertPre_seq(list1,0,12);
insertPre_seq(list1,1,22);
insertPre_seq(list1,2,32);
insertPost_seq(list1,3,43);
insertPost_seq(list1,3,53);
insertPost_seq(list1,4,63);
insertPost_seq(list1,1,73);
i=locate_seq(list1,73);
printf("%d",i);
return 1;
}
摘自 yucong
补充:软件开发 , C语言 ,