顺序表的生成、初始化、插入、删除

来源:互联网 发布:淘宝手机开店流程步骤 编辑:程序博客网 时间:2024/05/16 12:49

顺序表

#include <stdio.h>

#include <malloc.h>

#define MAXSIZE 100

#define OK 1

typedef int datatype;          //定义datatype的类型

typedef struct

               {

                      datatype a[MAXSIZE];

                      int last;

               }Seqlist;              //定义一个结构体,名字就是Seqlist

 

void CreatSeqlist(Seqlist *L)                     //创建顺序表

{

 

             int i;

                L->last = 0;

                printf("please input the list\n");

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

                {

                       scanf("%d",&L->a[i]);

                       L->last++;

                }

}

 

void OutputSeqlist(Seqlist *L)                     //输出顺序表

{

            int i;

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

                      printf("%d ",L->a[i]);

                      printf("\n");

}

int InsertSeqlist(Seqlist *L,int i,datatype x)      //把x插入到顺序表的i位置

{

 

           int j;

              if(L->last== MAXSIZE-1)

              {

                     printf("表满\n");

                     return0;

              }

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

              {

                     printf("位置错\n");               //检查插入位置的正确性

                     return0;

              }

              {

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

                     L->a[j+1]= L->a[j];             //结点后移

                  L->a[i-1] = x;                   //新元素插入

                     L->last++;                        //last仍然指向最后一个元素

                     OutputSeqlist(L);

              }

                     returnOK;

}

int DeleteSeqList(Seqlist *L,int i)

{

     int j;

 

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

         printf("Insertlocate ERROR!" );

 

     else

     {

         j=i;

         printf("Thedeleted element is:");

        printf("%d\n",L->a[j]);

         for(j=i;j<=L->last;j++)

           L->a[j-1]=L->a[j];

 

         L->last--;

         printf("Afterthe list is:\n");

         OutputSeqlist(L);

 

     }

     return OK;

}

 

int main()

{

       Seqlist L;

       int i;

       datatype x;

       CreatSeqlist(&L);

       printf("the listis\n");

       OutputSeqlist(&L);

        printf("please intput a element to insert\n");

        scanf("%d",&x);

        printf("please intput the position toinsert\n");

        scanf("%d",&i);

       InsertSeqlist(&L,i,x);

        printf("please intput the position todelete\n");

    scanf("%d",&i);

    DeleteSeqList( &L ,i);

 

 

    return 0;

}

0 0
原创粉丝点击