#include<stdio.h>
#include<stdlib.h>
#define N 50
typedef char elemtype;
typedef struct node
{
elemtype data[N];
int len;
}Node,*List;
void init(List L) //初始化链表长度为0
{
L->len=0;
}
int length(List L) //返回链表L的长度
{
return L->len;
}
void insert(List L,int pos,elemtype x) //将数据x插入链表L的pos位
{
if(pos<1||pos>L->len+1) //判断位置是否存在
{
printf("insert error\n"); //不存在
}
else
{
L->len++; //存在
for(int j=L->len;j>=pos;j--)
{
L->data[j]=L->data[j-1];
}
L->data[pos-1]=x;
}
}
void print(List L)
{
for(int i=1;i<L->len;i++)
{
printf("%c->",L->data[i-1]);
}
printf("%c\n",L->data[L->len-1]);
}
elemtype getnode(List L,int pos) //查询链表第pos位的数据是多少
{
if(pos<1||pos>L->len)
{
printf("error");
}
else
{
return L->data[pos-1];
}
}
int locate(List L,elemtype x) //查询链表等于x的元素位于第几位
{
int i=0;
while(i<L->len&&L->data[i]!=x)
{
i++;
}
if(i==L->len)
{
return -1;
}
return i+1;
}
void delnode(List L,int pos) //删除链表L的pos位上的元素
{
if(pos<1||pos>L->len)
{
printf("del error\n");
}
else
{
for(int j=pos;j<L->len;j++)
{
L->data[j-1]=L->data[j];
L->len--;
}
}
}
int main()
{
int i=1;
Node L;
printf("**********顺序表演示程序**********\n");
printf("* *\n");
printf("* *\n");
printf("* *\n");
printf("* *\n");
printf("* *\n");
printf("* *\n");
printf("**********************************\n\n");
printf("请输入你想建立的顺序表元素,以?结束:\n");
char ch;
char num;
int poss;
char x;
int n;
ch=getchar();
while(ch!='?')
{
insert(&L,i,ch); //将ch插入链表L的i位
i++;
ch=getchar();
}
printf("你建立的顺序表为:\n");
print(&L);
printf("顺序表的长度为:\n");
printf("%d\n",L.len);
printf("输入你想查找的元素:\n");
fflush(stdin); //刷新缓冲区,将缓冲区内的数据清空并丢弃,其实也就是把回车键吃掉
scanf("%c",&num);
printf("你想查找的元素为:\n");
printf("%c\n",num);
printf("它的序位为:\n");
printf("%d\n",locate(&L,num));
printf("输入你想查找的元素序位:\n");
scanf("%d",&poss);
printf("你想查找的元素序位为:\n");
printf("%d\n",poss);
printf("该序位的元素为:\n");
printf("%c\n",getnode(&L,poss));
printf("输入你想插入的元素及序位(中间用逗号隔开):\n");
fflush(stdin);
scanf("%c,%d",&x,&n);
insert(&L,n,x);
printf("插入后顺序表为:\n");
print(&L);
fflush(stdin);
printf("请输入你想删除的元素序位:\n");
scanf("%d",&n);
delnode(&L,n);
printf("删除后的顺序表为:\n");
print(&L);
}