用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;
}

发布了84 篇原创文章 · 获赞 46 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/gufenchen/article/details/104188464
今日推荐