C++ 实现线性表顺序存储结构的插入与删除

主函数:

#include 
typedef int eletype;

const int MaxSize = 25;

struct Sqlist
{
    eletype arr[MaxSize];
    int length;
};

void getArr(Sqlist & sqlist);
void showArr(const Sqlist sqlist);
Sqlist insertArr(Sqlist sqlist);
Sqlist deleteArr(Sqlist sqlist);

int main()
{
    Sqlist sqlist;
    getArr(sqlist);
    showArr(sqlist);
    Sqlist sqlist2 = insertArr(sqlist);
    showArr(sqlist2);
    //showArr(sqlist);
    Sqlist sqlist3 = deleteArr(sqlist);
    showArr(sqlist3);

    system("pause");
    return 0;
}

各个实现函数:

#include 
typedef int eletype;

const int MaxSize = 25;

struct Sqlist
{
    eletype arr[25];
    int length;
};

void getArr(Sqlist & sqlist);
void showArr(const Sqlist sqlist);
Sqlist insertArr(Sqlist sqlist);
Sqlist deleteArr(Sqlist sqlist);

void getArr(Sqlist & sqlist)
{
    int n;
    std::cout << "Please enter the length of Array: ";
    std::cin >> n;
    while (n > MaxSize || n < 0)
    {
        std::cout << "The input is error, please enter a number ranges 0 to " << MaxSize << std::endl;
        std::cin >> n;
    }
    int i;
    for (i = 0; i < n; i++)
    {
        std::cout << "Please enter the " << i << "-th element:";
        std::cin >> sqlist.arr[i];
    }
    sqlist.length = n;
}

void showArr(const Sqlist sqlist)
{
    using std::cout;
    using std::endl;
    for (int j = 0; j < sqlist.length; j++)
    {
        cout << "The " << j << "-th element is " << sqlist.arr[j] << endl;
    }
    cout << "The length of this array is " << sqlist.length << endl;
}

Sqlist insertArr(Sqlist sqlist)
{
    using namespace std;
    int m;
    cout << "Please enter a location of insert:\n";
    cin >> m;
    while (m<0 || m>sqlist.length)
    {
        cout << "The location of insert is error, please enter a location ranges 0 to " << sqlist.length << endl;
        cin >> m;
    }
    int j;
    for (j = sqlist.length; j > m; j--)
    {
        sqlist.arr[j] = sqlist.arr[j - 1];
    }
    eletype value;
    cout << "Please enter a element in location of " << m << ": " << endl;
    cin >> value;
    sqlist.arr[m] = value;
    sqlist.length = sqlist.length + 1;
    return sqlist;
}

Sqlist deleteArr(Sqlist sqlist)
{
    using namespace std;
    int index;
    cout << "Please enter a location of delete element: ";
    cin >> index;
    while (index<0 || index>sqlist.length - 1)
    {
        cout << "The location is error, please enter a location ranges 0 to " << sqlist.length - 1 << endl;
        cin >> index;
    }
    for (int j = index; j < sqlist.length - 1; j++)
    {
        sqlist.arr[j] = sqlist.arr[j + 1];
    }
    sqlist.arr[sqlist.length - 1] = '\0';
    sqlist.length = sqlist.length - 1;
    return sqlist;

}

你可能感兴趣的:(C++)