线性表之一:顺序表的实现(详)

#include<iostream>
using namespace std;
#define MAXSIZE 100 //注意宏定义不能加“;”,有时候会犯错!!!
typedef int DataType;
class SeqList

private:
DataType list[MAXSIZE]; //定义数组list,用数组来实现线性表
int length; //线性表list的长度,即元素个数
public:
SeqList(){length = 0;}    //构造函数,初始化length
void creat_sr_list(int n); //创建初始线性表list
int sq_insert(int i, DataType x); //在list的第i个位置插入元素x
int sq_del(int i); //删除list中的第i个元素
DataType SLGet(int i); //获取list的第i个元素
DataType SLSum(); //计算list所有元素之和
int SLIsEmpty(); //判断list是否为空
void SLPrint(); //打印list中的元素
};

void SeqList::creat_sr_list(int n)
{
DataType value;
for(int i = 0; i < n; i++)
{
         cin >> value;
         list[i] = value;
length++;
     }
}

int SeqList::sq_insert(int i, DataType x)
{
if((i < 0) || (i > length))
return 1;
    if(length >= MAXSIZE)
return 2;
    for(int j = length-1; j >= i; j--)
    {
        list[j + 1] = list[j];   
    }
    list[i] = x;
    length++;
    return 0;
}

int SeqList::sq_del(int i)
{
if((i < 0) || (i >= length))
return 1;
    if(length >= MAXSIZE)
return 2;
    for(int j = i + 1; j < length; j++)
list[j - 1] = list[j];
    length--;
    return 0;  
}

DataType SeqList::SLGet(int i) 
{
if((i < 0) || (i > length))
return 1;
return list[i];
}


DataType SeqList::SLSum()
{
DataType sum = 0;
for(int i = 0; i < length; i++)
sum += list[i];
return sum;
}

int SeqList::SLIsEmpty()
{
if(length == 0)
{
cout << "the list is empty" << endl;
return -1;
}
else
{
cout << "the list is not empty" << endl;
return 0;
}
}

void SeqList::SLPrint()
{
for(int i = 0; i < length; i++)
cout << list[i] << ends;
cout << endl;
}

int main()
{
SeqList list_object;
list_object.creat_sr_list(10);
list_object.SLIsEmpty(); //判断该表是否为空

cout << "print original list:" << endl;
list_object.SLPrint();

list_object.sq_insert(3, 900);
cout << "print the list that has been inserted element:" << endl;
list_object.SLPrint();

list_object.sq_del(2); //调用删除元素的函数
cout << "print the list that has been delete element:" << endl;
list_object.SLPrint();

cout << "get the element from the list is:";
cout << list_object.SLGet(4) << endl;

cout << "get the sum of all list's elements:";
cout << list_object.SLSum() <<  endl;
return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值