顺序表的基本操作

#include<stdio.h>

#include<stdlib.h>

#define maxsize 1000

typedef char elemtype;

 

typedef struct

{

 elemtype list[maxsize];

 int length;

}sequenlist;

 

void creatlist(sequenlist *L)

{

 int n,i;

 char tmp;

 printf("请输入数据的个数:\n");

 scanf("%d",&n);

 printf("请按顺序输入各个值:\n");

 for(i=0;i<n;i++)

 {

  printf("list[%d]=",i);

  fflush(stdin); // 清空输入缓冲区,通常是为了确保不影响后面的数据读取。

  scanf("%c",&tmp);

  L->list[i]=tmp;

 }

 L->length=n;

 printf("\n");

}

 

//插入元素

int insert(sequenlist *L,elemtype x,int i) //i用来表示插入位置

{

 int j;

 if(L->length==maxsize)

 {

  printf("overflow\n");

  return 0;

 }

 else if((i<1)||(i>L->length+1)) //length+1表示在表尾插入

 {

  printf("error,please input the right'i'\n");

  return 0;

 }

 else

 {

  for(j=L->length-1;j>=i-1;j--)

   L->list[j+1]=L->list[j];

     L->list[i-1]=x; 

  L->length=L->length+1; 

  return 1;

 }

 

}

 

//删除元素

int dellist(sequenlist *L,int i) //i表示删除的位置

{

 if((i<1)||(i>L->length))

 {

  printf("error,please input the right 'i'\n");

  return 0;

 }

 else

 {

  for(;i<L->length;i++)

   L->list[i-1]=L->list[i];

  L->length=L->length-1;

  return 1;

 }

}

 

void printout(sequenlist *L)

{

 int i;

 for(i=0;i<L->length;i++)

 {

  printf("list[%d]=",i);

  printf("%c\n",L->list[i]);

 }

}

int main()

{

 sequenlist *L;

 char cmd,x;

 int i;

 L=(sequenlist *)malloc(sizeof(sequenlist));

 creatlist(L);

 printout(L);

 do

 {

  printf("i,I...插入\n");

  printf("d,D...删除\n");

  printf("q,Q...退出\n");

  do

  {

   fflush(stdin);

   scanf("%c",&cmd);

  }

  while((cmd!='d')&&(cmd!='D')&&(cmd!='q')&&(cmd!='Q')&&(cmd!='i')&&(cmd!='I'));

  switch(cmd)

  {

  case'i':

  case'I':

   printf("请输入要插入的数据:");

   fflush(stdin);

   scanf("%c",&x);

   printf("请输入要插入的位置:");

   scanf("%d",&i);

   insert(L,x,i);

   printout(L);

   break;

  case'd':

  case'D':

   printf("请输入要删除的数据的位置:");

   fflush(stdin);

   scanf("%d",&i);

   dellist(L,i);

   printout(L);

   break;

  }

 }

 while((cmd!='q')&&(cmd!='Q'));

}

 

b688805eb925496191097b03f14567ca.jpg

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值