数据结构实验2-1

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cd1202/article/details/51052291

编写一个程序2-1.cpp,实现顺序表的基本运算(假设顺序表的元素类型为char),并在此基础上设计一个程序2-1.cpp,完成如下功能:

(1)初始化顺序表L;

(2)采用尾插法依次插入元a,b,c,d,e;

(3)输出顺序表L;

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

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

(6)判断顺序表L的第3个元素;

(7)输出元素a的位置;

(8)在第4个元素位置上插入元素f;

(9)输出顺序表L;

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

(11)输出顺序表L;

(12)释放顺序表L.

#include <iostream>
#include <malloc.h>
using namespace std;
typedef char
ElemType;
typedef class Sqlist{
    public:
    ElemType data[100];
    int length;
};
void InitList(Sqlist *&L)
{
    L=(Sqlist * )malloc(sizeof(Sqlist));
    L->length=0;
}
void DispList(Sqlist *L)   //输出元素
{
    for(int i=0;i<L->length;i++)
    {
        cout<<L->data[i]<<" ";
    }
    cout<<endl;
}
void ListLength(Sqlist *L)   //输出长度
{
    cout<<L->length<<endl;
}
bool ListEmpty(Sqlist *L)   //判断线性表是否为空
{
    return(L->length==0);
}
bool GetElem(Sqlist *L,int i)     //输出线性表第e个元素
{
    if(i<1||i>L->length)
        return false;
    cout<<L->data[i-1]<<endl;
    return true;
}
int LocateElem(Sqlist *L,ElemType e)        //输出指定元素位置
{
    int i=0;
    while(i<L->length&&L->data[i]!=e)
        i++;
    if(i>=L->length)
        return 0;
    else
        return i+1;
}
bool ListInsert(Sqlist *L,int i,ElemType e)    //在第i个元素位置上插入元素e
{
    int j;
    if(i<1||i>L->length+1)
        return false;
    i--;
    for(j=L->length;j>i;--j)
        L->data[j]=L->data[j-1];
    L->data[i]=e;
    L->length++;
    return true;
}
bool ListDelect(Sqlist *L,int i,ElemType e)     //删除数据元素
{
    int j;
    if(i<1||i>L->length+1)
        return false;
    i--;
    e=L->data[i];
    for(j=i;j<L->length;++j)
        L->data[j]=L->data[j+1];
    L->length--;
    return true;
}
void DestroyList(Sqlist *&L)                //销毁线性表
{
    free(L);
}

int main()
{
    Sqlist *L;
    cout<<"(1)初始化线性表"<<endl;
    InitList(L);
    cout<<"(2)采用尾插法依次插入元素a,b,c,d,e"<<endl;
	ListInsert(L,1,'a');
	ListInsert(L,2,'b');
	ListInsert(L,3,'c');
	ListInsert(L,4,'d');
	ListInsert(L,5,'e');
    cout<<"(3)输出顺序表L:";
    DispList(L);
    cout<<"(4)顺序表L的长度=";
    ListLength(L);
    cout<<"(5)判断顺序表是否为空?";
    if(ListEmpty(L))
        cout<<"顺序表为空!"<<endl;
    else
        cout<<"顺序表非空!"<<endl;
    cout<<"(6)顺序表的第三个元素=";
    GetElem(L,3);
    cout<<"(7)元素a的位置:";
    cout<<LocateElem(L,'a')<<endl;
    cout<<"(8)在第四个位置插入元素f";
    ListInsert(L,4,'f');
    cout<<endl;
    cout<<"(9)输出顺序表:";
    DispList(L);
    cout<<"(10)删除线性表L第三个元素";
    ListDelect(L,3,'e');
    cout<<endl;
    cout<<"(11)输出顺序表:";
    DispList(L);
    cout<<"(12)释放线性表"<<endl;
    DestroyList(L);
    return 0;
}

运行结果:


猜你喜欢

转载自blog.csdn.net/cd1202/article/details/51052291
2-1