Example data structure sequence table operation

  • 2020-04-02 02:16:58
  • OfStack


#include<stdio.h>
#include<malloc.h>
#define maxsize 1024
typedef char datatype;
typedef struct
{
 datatype data[maxsize];
 int last;
}sequenlist;


int insert(sequenlist *L,datatype x,int i)
{
 int j;
 if(L->last==maxsize-1)
 {
  printf("overflow");
  return 0;
 }
 else if((i<0)||(i>L->last))
 {
  printf("error,please input the right 'i'");
  return 0;
 }
 else
 {
  for(j=L->last;j>=i;j--)
  {
   L->data[j+1]=L->data[j];
   L->data[i]=x;
   L->last=L->last +1;
  } 
 }
  return(1);
}


int dellist(sequenlist *L,int i)
{
 if((i<0)||(i>L->last))
 {printf("error,please input the right 'i'");
 return 0;}
 else
  {
   for(;i<L->last ;i++)
    L->data[i]=L->data[i+1];
    L->last =L->last-1;
    return(1);
  }
}


void createlist(sequenlist *L)
{
 int n,i;
 char tmp;
 printf(" Please enter the number of elements: n");
 scanf("%d",&n);
 for(i=0;i<n;i++)
 {
  printf("data[%d]=",i);
  fflush(stdin);
  scanf("%c",&tmp);
  L->data[i] =tmp;
 }
 L->last=n-1;
 printf("/n");
}


void printflist(sequenlist *L)
{
 int i;
 for(i=0;i<L->last ;i++)
 {
  printf("data[%d]=",i);
  printf("%cn",L->data [i]);
 }
}

main()
{
 sequenlist *L;
 char cmd,x;
 int i;
 L=(sequenlist *)malloc(sizeof(sequenlist));  
 createlist(L);
 printflist(L);
 do
 {
  printf("i,I... insert n");
  printf("d,D... delete n");
  printf("q,Q... exit 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(" Please enter the data you want to insert: ");
   fflush(stdin);
   scanf("%c",&x);
   printf(" Please enter the position you want to insert: ");
   scanf("%d",&i);
   insert(L,x,i);
   printflist(L);
   break;

  case 'd':
  case 'D':
   printf(" Please enter the location of the element you want to delete: ");
   fflush(stdin);
   scanf("%d",&i);
   dellist(L,i);
   printflist(L);
   break;
 }
 }while((cmd!='q')&&(cmd!='Q'));
}


Related articles: