用C语言编写顺序表的插入写法

#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define OVERFLOW 0 
#define ERROR -1
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10

typedef struct
{
  char *elem;
  int length;  //当前长度
  int listsize;  //线性表的长度
}SqList,L;

/*线性表的初始化*/
int Initlist(SqList *L)
{
  L->elem=(char *)malloc(LIST_INIT_SIZE*sizeof(char));
  if(!L->elem)
    exit(OVERFLOW);
  L->length=0;
  L->listsize=LIST_INIT_SIZE;
  return OK;
}

int ListInsert_Sq(SqList *L,int i,char e)
{
  /*特殊情况的处理*/
  if(i<1||i>L->length)
  return ERROR;
  char *newbase;
  char *p,*q;
 if(L->length>=L->listsize)  //是否满
 {
   newbase=(char*)realloc(L->elem,(L->listsize + LISTINCREMENT)*sizeof(char));
   if(!newbase)
     exit(OVERFLOW);
   L->elem=newbase;
   L->listsize+=LISTINCREMENT;
 } 
 
  /*插入具体操作*/
  q=&(L->elem[i-1]);  //q为第i个元素的位置
  for(p=&(L->elem[L->length-1]);p>=q;p--)
  {
    *(p+1)=*p;
    *q=e;
    L->length++;
  }
  return OK;
}

int main()
{
  int y;
  SqList L;
  Initlist(&L);
  int i;
  printf("please input the data:");
  for(i=0;i<10;i++)
  {
    scanf("%c",&L.elem[i]);
    L.length++;
  }
  ListInsert_Sq(&L,2,'a');
  printf("the final array is:");
  for(i=0;i<L.length;i++)
  { 
    printf("%c",L.elem[i]);
  }
  return 0;
}

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值