顺序表结构的定义与基本操作

116 阅读1分钟
#include<iostream>
#include<stdio.h>
#define MAXSIZE 100
using namespace std;
typedef struct
{
    int *data;
    int length;
} Sqlist;

//初始化
void Init(Sqlist &L)
{
    L.data=new int[MAXSIZE];   //动态分配
    if(!L.data)
        cout<<"空间分配失败!\n";
    else
    {
        cout<<"空间分配成功!\n";
        L.length=0;
    }
}

//建表
void Creat(Sqlist &L)
{
    cout<<"顺序表建立成功\n\n请输入表长:";
    cin>>L.length;
    cout<<"表中元素为:";
    for(int i=0; i<L.length; i++)
        cin>>L.data[i];
}

//输出
void Print(Sqlist &L)
{
    for(int i=0; i<L.length; i++)
        cout<<L.data[i]<<"  ";
    cout<<endl<<endl;
}

//插入
void Insert(Sqlist &L,int index,int x)
{
    if(index<1||index>L.length+1)
        cout<<"位置不合理"<<endl;
    else if(L.length==MAXSIZE)
        cout<<"表满"<<endl;
    else
    {
        for(int j=L.length-1; j>=index-1; j--)
            L.data[j+1]=L.data[j];//插入位置及之后的元素后移
        L.data[index-1]=x; //将新元素x放入第index个位置
        L.length++;  //表长加1
    }
    Print(L);
}

//删除
void Delete(Sqlist &L,int index)
{
    if(index<1||index>L.length)
        cout<<"位置不合理"<<endl;
    else if(L.length==0)
        cout<<"空表"<<endl;
    else
    {
        //int e = L.data[index-1]; //将欲删除的元素保存下来
        for(int j=index; j<=L.length-1; j++)
            L.data[j-1]=L.data[j];//被删除元素之后的元素前移
        L.length--;  //表长减1
    }
    Print(L);
}

//按位置查找
void IdSearch(Sqlist &L,int index)
{
    if(index<1||index>L.length)
        cout<<"查找的位置不存在"<<endl<<endl;
    else
        cout<<L.data[index-1]<<endl<<endl;
}

//按值查找
int ValueSearch(Sqlist &L,int e)
{
    for(int i=0; i<L.length; i++)
        if(L.data[i]==e)
            return i+1;
    return 0;
}


int main()
{
    int Insert_Number,Insert_Location,Delete_Location,Seach_Id,Seach_Value;
    Sqlist L;
    Init(L);

    Creat(L);
    Print(L);

    cout<<"请输入要插入的结点值及其位置:";
    cin>>Insert_Number>>Insert_Location;
    Insert(L,Insert_Location,Insert_Number);

    cout<<"请输入要删除的结点的位置:";
    cin>>Delete_Location;
    Delete(L,Delete_Location);


    cout<<"请输入要查找的结点的序号:";
    cin>>Seach_Id;
    IdSearch(L,Seach_Id);

    cout<<"请输入要查找的结点的值:";
    cin>>Seach_Value;
    if(!ValueSearch(L,Seach_Value))
        cout<<"输入的元素"<<Seach_Value<<"不在顺序表中"<<endl<<endl;
    else
        cout<<"输入的元素"<<Seach_Value<<"在顺序表的第"<<ValueSearch(L,Seach_Value)<<"位"<<endl<<endl;
}