C++顺序表(十四)

来源:互联网 发布:js将字符串向下取整 编辑:程序博客网 时间:2024/05/18 02:27
  • 顺序表是在计算机内存中以数组的形式保存的线性表,是指用一组地址连续的存储单元依次存储数据元素的线性结构。线性表采用顺序存储的方式存储就称之为顺序表。顺序表是将表中的结点依次存放在计算机内存中一组地址连续的存储单元中。

如果每次只加一个值进入表中,用数组就行了,如果要加入多个值,就可以使用结构体。

顺序表一般有这几个操作:

1、输入数据

2、查找数据

3、插入数据

4、删除数据

【代码示例】

#include <iostream>#include <cstdlib>using namespace std;int Error = 0;#define MAXLISTLEN 100int ListLen = 0;int SeqList[MAXLISTLEN + 1];//顺序表查找int SearchSeqList(int i){    if ((i > ListLen) || (i < 1) || (ListLen == 0)){     Error = -1; return (-1);    //查找出错返回}else{ return SeqList[i];    //返回指定位置的元素值}}//顺序表的插入 void InsertSeqList(int NewItem, int i){int j;if ((i > ListLen + 1) || (i < 1) || (ListLen == MAXLISTLEN)){Error = -2;    //插入出错返回cout << "插入出错啦!!!";}    else{for (j = ListLen; j >= i; j--)    //从后往前移{SeqList[j + 1] = SeqList[j];}SeqList[i] = NewItem;        //插入新元素ListLen = ListLen + 1;        //表长加一}} //顺序表指定位置数据的删除void DeleteSeqList(int i){int j;if ((i > ListLen) || (i < 1) || (ListLen == 0)){Error = -3;    //删除出错返回cout << "删除出错啦!!!";}    else{for (j = i; j < ListLen; j++)    //从前往后移{SeqList[j] = SeqList[j + 1];}ListLen = ListLen - 1;        //表长减一}} //顺序表显示 void ShowSeqList(){int i;cout << "The list : ";for (i = 1; i <= ListLen; i++){cout << SeqList[i] << " ";    //逐个显示数据元素}cout << endl;            //换行} //主函数int main(int argc, char * argv[]){int r[MAXLISTLEN], i, SearchPos, NewPos, NewItem, DelPos, switch_on;cout << "Please input the ListLen : ";cin >> ListLen;    //输入样本数目(表长)//创建顺序表for (i = 1; i <= ListLen; i++){cout << "Please input No." << i << "Item : ";cin >> SeqList[i];}ShowSeqList();    //显示顺序表while (true){cout << "请输入你想要的操作序号:\n" << "1、查找位置" << "\t2、插入数据" << "\t3、删除数据\t";cin >> switch_on;switch (switch_on){case 1:cout << "Please input the search pos : ";cin >> SearchPos;    //输入查找位置cout << "Your Searched Item is : " << SearchSeqList(SearchPos) << endl;    //输出查找的数据元素值break;case 2:cout << "Please input the NewPos where you want to insert : ";cin >> NewPos;        //插入位置输入cout << "Please input the NewItem what you want to insert : ";cin >> NewItem;    //插入元素输入InsertSeqList(NewItem, NewPos);    //新数据插入顺序表中cout << "After insert : ";ShowSeqList();        //插入数据后,输出新的顺序表break;case 3:cout << "Please input the DelPos where you want to delete : ";cin >> DelPos;        //输入删除元素位置DeleteSeqList(DelPos);    //按位置删除数据cout << "After delete : ";ShowSeqList();break;default:break;}}if (Error < 0) cout << "Error" << Error << endl;system("pause");return 0;}
【演示结果】