#include<stdio.h>
#include<stdlib.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define OVERFLOW -2
typedef int Status;
typedef char ElemType;
typedef struct{
ElemType *elem;
int length;//当前链表长度
int listsize;//当前分配的存储容量
}SqList;
//初始化单链表
SqList InitList(SqList &L)
{
L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem)exit(OVERFLOW);
L.length=0;
L.listsize=LIST_INIT_SIZE;
return L;
}
//输出顺序表
void PrintList(SqList &L)
{
int i=0;
for(i=0;i<L.length;i++)
{
printf("%d ",L.elem[i]);
}
}
//给顺序表赋值
SqList Assignment(SqList &L,int x)
{
int i;
printf("请输入顺序表的值:\n");
for(i=0;i<x;i++)
{
scanf("%d",&L.elem[i]);
L.length++;
}
return L;
}
//顺序表的插入
SqList InsertList(SqList &L,int i,ElemType x)//i是插入位置,x是插入的值
{
if(i<0||i>L.length+1) printf("Flause");
if(L.length>=L.listsize)//当前存储空间满了,增加分配
{
L.elem=(ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
if(!L.elem)exit(OVERFLOW);
L.listsize+=LISTINCREMENT;//增加存储容量
}
for(int j=i-1;j<L.length;j++)
{
L.elem[j+1]=L.elem[j];
}
L.elem[i-1]=x;
L.length+=1;
return L;
}
//顺序表的删除
SqList DeleteList(SqList &L,int i)//i是删除的位置
{
if(i<0||i>L.length)printf("Flause");
printf("删除的元素是:%d\n",L.elem[i-1]);
for(int j=i-1;j<L.length;j++)
{
L.elem[j]=L.elem[j+1];
}
L.length--;
return L;
}
//顺序表的按值查找
void FindList(SqList &L,int x)//查找的元素
{
int i=-1;
for(int j=0;j<L.length;j++)
{
if(L.elem[j]==x)
i=j+1;
}
if(i==-1)
{
printf("没找到!\n");
}
else
{
printf("找到了,是第%d个元素\n",i);
}
}
int main()
{
SqList L;
int a,x,b,c;
L=InitList(L);
Assignment(L,5);
PrintList(L);
printf("\n");
printf("请插入一个元素:\n");
scanf("%d%d",&a,&x);
InsertList(L,a,x);
printf("请输出插入后的顺序表:\n");
PrintList(L);
printf("\n");
printf("请输入删除元素的位置:\n");
scanf("%d",&b);
DeleteList(L,b);
printf("请输出删除后的顺序表:\n");
PrintList(L);
printf("\n");
printf("请输入查找的元素:\n");
scanf("%d",&c);
FindList(L,c);
system("pause");
return 0;
}
数据结构——顺序表
最新推荐文章于 2024-09-09 19:10:22 发布