将线性表的结点按逻辑次序依次存放在一组地址连续的存储单元里.用这中方法存储的线性表称为顺序表(Sequential List)
一般可以用数组来描述顺序表.下面以C语言数组方式实现顺序表,及顺序表的基本运算
# include <stdlib.h>
# include <stdio.h>
# define ListSize 100
typedef int DataType;
typedef struct
{
DataType data[ListSize];
int length;
}Seqlist; //定义顺序表的结构类型
/*错误信息输出函数*/
void Error(char *message)
{
fprintf(stderr,"Error:%s/n",message); //输出错误信息
exit(1);//终止程序,返回1给操作系统
}
/*定义顺序表*/
Seqlist initList(int listsize)
{
int i;
Seqlist sqlist;
sqlist.length=listsize;
for(i=0;i<listsize;i++)
{
int data;
scanf("%d",&data);
sqlist.data[i]=data;
}
return sqlist;
}
/*取得顺序表的长度*/
int getLength(Seqlist list)
{
return list.length;
}
/*取得顺序表中索引为i的数据*/
DataType getNode(Seqlist list,int i)
{
return list.data[i];
}
/*向顺序表中查入数据*/
void insertNode(Seqlist *list,DataType dt,int i)
{
int j;
if(i<0||i>list->length+1)
{
Error("position error");
}
if(list->length>=ListSize)
{
Error("overflow");
}
for(j=list->length-1;j>=i-1;j--)
{
list->data[j+1]=list->data[j];
}
list->data[i-1]=dt;
list->length++;
}
/*将顺序表中的数据移出*/
void deleteNode(Seqlist *list,int i)
{
int j;
if(i<0||i>list->length)
{
Error("position error");
}
for(j=i;j<=list->length-1;j++)
{
list->data[j-1]=list->data[j];
}
list->length--;
}
/*输出顺序表*/
void printList(Seqlist sqlist)
{
int i;
int listsize=sqlist.length;
printf("List size=%d/n",sqlist.length);
for(i=0;i<listsize;i++)
{
printf("list data[%d]=%d/n",i,sqlist.data[i]);
}
}
void main()
{
int listsize=5;
Seqlist sqlist;
Seqlist *list;
DataType dt;
printf("Please init list/n");
sqlist=initList(5);
list=&sqlist;
printf("the list is:/n");
printList(sqlist);
printf("insert node to 2/n");
insertNode(list,0,2);
printList(sqlist);
deleteNode(list,6);
printList(sqlist);
dt=getNode(sqlist,3);
printf("getnode 3 %d/n",dt);
}