//顺序表的初始化,建立,插入,查找,删除。//
//Author:Wang Yong //
//Date: 2010.8.19 //
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100 //定义顺序表的最大容量
#define ElemType int //定义顺序表存储的类型,可自行设置
//顺序存储结构的线性表的类型
typedef struct
{
ElemType data[MAXSIZE];//存放线性表的数组
int length; //length是线性表的长度
} SeqList;
//
//顺序表的初始化
SeqList SeqListInit()
{//构造一个空的线性表L,时间复杂度O(1)
SeqList L;//定义一个顺序表
L.length = 0; //顺序表的长度为0
return L;//返回空顺序表
}
/
//顺序表的建立
SeqList SeqlistCreate(SeqList L)
{
ElemType x;
while(scanf("%d",&x) != EOF)//存储顺序表的元素
{
L.data[L.length] = x;
L.length++;
}
return L;
}
///
//顺序表的插入
SeqList SeqlistInsert(SeqList L, int i, ElemType x)
{//在顺序表中的第i个位置插入元素x
if(L.length == MAXSIZE)
printf("表已经满了\n");//插入时,必须检查表是否已经满了。否则会出现溢出错误
else if(i < 1 || i > L.length)
printf("插入位置错误\n");//判断插入位置的有效性
int j;
for(j = L.length-1; j >= i - 1; j--)//第i个位置元素逐个后移
L.data[j+1] = L.data[j];
L.data[i-1] = x; //插入元素x
L.length++; //顺序表长度增1
return L;
}
//
//GetElem(SqList L, int i)查找顺序表L中第i个数据元素,直接在表中定位,并返回L.elem[i-1]
ElemType SeqListGetElem(SeqList L,int i)
{//
if(i < 1 || i > L.length)
{
printf("查找位置错误!\n");//检查查询位置是否合法
return 0;
}
else
return L.data[i-1];
}
//
//LocateElem(SqList &L, ElemType e)查找顺序表L中与给定值e相等的数据元素,若找到
//与e相等的第1个元素则返回该元素在顺序表中的序号;否则查找失败返回0
int SeqListLocateElem(SeqList L,ElemType x)
{//在顺序表L中查找值为X的元素。
int i = 0;
while(i <= L.length && L.data[i] != x)
i++;
if(i <= L.length) return i+1; //返回数据元素的位置。
else return 0;
}
SeqList SeqListDelete(SeqList L,int i)
{//删除顺序表中的第i个位置的元素
if(i < 1 || i > L.length)
printf("删除位置错误\n"); //检查删除位置是否合法
int j;
for(j = i-1; j < L.length; j++)
L.data[j] = L.data[j+1]; //将第i个位置之后的元素前移
L.length--; //顺序表长度-1
return L;
}
//
int main()
{
SeqList seqlist;
seqlist = SeqListInit();
int i;
ElemType x;
printf("创建一个顺序表,请输入顺序表的元素:");
seqlist = SeqlistCreate(seqlist);
for(i = 0 ; i < seqlist.length;i++)
printf("%d ",seqlist.data[i]);
printf("\n%d\n",seqlist.length);
printf("请输入要查找元素的位置:");
scanf("%d",&i);
x = SeqListGetElem(seqlist,i);
if(x)
printf("%d\n",x);
printf("请输入要查找元素的值:");
scanf("%d",&x);
i = SeqListLocateElem(seqlist , x);
if(i)
printf("在顺序表中的位置为%d\n",i);
else
printf("没有找到!\n");
printf("请输入插入元素位置:");
scanf("%d",&i);
printf("请输入插入元素的值:");
scanf("%d",&x);
seqlist = SeqlistInsert(seqlist,i,x);
for(i = 0 ; i < seqlist.length;i++)
printf("%d ",seqlist.data[i]);
printf("\n%d\n",seqlist.length);
printf("请输入删除元素位置:");
scanf("%d",&i);
seqlist = SeqListDelete(seqlist,i);
for(i = 0 ; i < seqlist.length;i++)
printf("%d ",seqlist.data[i]);
printf("\n%d\n",seqlist.length);
return 0;
}
转载于:https://www.cnblogs.com/newwy/archive/2010/10/10/1847449.html