顺序表基本操作

实验题目;顺序表基本操作

实验目的;1.掌握用 C/C++语言调试程序的基本方法。

2.掌握线性表的基本运算,如插入、删除等。

•  实验内容;编写程序实现顺序表的各种基本运算,并在此基础上设计一个主程序完成如下功能:

•  (1)初始化顺序表L;

•  (2)依次在L尾部插入元素-1,21,13,24,8;

•  (3)输出顺序表L;

•  (4)输出顺序表L长度;

•  (5)判断顺序表L是否为空;

•  (6)输出顺序表L的第3个元素;

•  (7)输出元素24的位置;

•  (8)在L的第4个元素前插入元素0;

•  (9)输出顺序表L;

•  (10)删除L的第5个元素;

(11)输出顺序表L

#include <stdio.h>
#include <malloc.h>
#define MaxSize 50
typedef int ElemType;
typedef struct
{  ElemType elem[MaxSize];
   int length;
}SqList;

void InitList(SqList *&L)
{  L= ( SqList *)malloc(sizeof(SqList));
   L -> length = 0;
}

void DestroyList(SqList *L)
{
   free(L);
}

int ListEmpty(SqList *L)
{
   return(L -> length == 0);
}

int ListLength(SqList *L)
{
   return(L -> length);
}

void DispList(SqList *L)
{  int i;
   if (ListEmpty(L))
   return;
   for (i = 0; i < L -> length; i++)
   printf("%d ",L -> elem[i]);
   printf("\n");
}

int GetElem(SqList *L,int i,ElemType &e)
{
    if (i < 1 || i > L -> length)
      return 0;
    e = L -> elem[i-1];
    return 1;
}

int LocateElem(SqList *L, ElemType e)
{
    int i = 0;
    while(i < L -> length && L->elem[i]!=e)
        i++;
    if (i>=L->length)
       return 0;
    else
       return i+1;
}

int ListInsert(SqList *&L,int i,ElemType e)
{  int j;
   if (i < 1 || i > L -> length + 1)
      return 0;
   i--;
   for (j = L -> length; j > i; j--)
      L -> elem[j]= L -> elem[j-1];
   L -> elem[i] = e;
   L -> length++;
   return 1;
}

int ListDelete(SqList *&L,int i,ElemType &e)
{  int j;
   if (i < 1 || i > L -> length)
      return 0;
   i--;
   e = L -> elem[i];
   for (j = i; j < L -> length - 1; j++)
      L -> elem[j] = L -> elem[j + 1];
   L -> length--;
   return 1;
}

int main()
{
    SqList *L;
    ElemType e;
    printf("初始化顺序表L\n");
    InitList(L);
    printf("依次采用尾插法插入-1,21,13,24,8元素\n");
    ListInsert(L,1,-1);
    ListInsert(L,2,21);
    ListInsert(L,3,13);
    ListInsert(L,4,24);
    ListInsert(L,5,8);
    printf("输出顺序表L:");
    DispList(L);
    printf("顺序表L长度=%d\n",ListLength(L));
    printf("顺序表L为%s\n",(ListEmpty(L)?"空":"非空"));
    GetElem(L,3,e);
    printf("顺序表L的第3个元素=%d\n",13);
    printf("元素24的位置=%d\n",LocateElem(L,24));
    printf("在第4个元素位置上插入元素0\n");
    ListInsert(L,4,0);
    printf("输出顺序表L:");
    DispList(L);
    printf("删除L的第5个元素\n");
        ListDelete(L,5,e);
    printf("输出顺序表L:");
    DispList(L);
    printf("释放顺序表L\n");
    DestroyList(L);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值