线性表(顺序储存)
#include<iostream> using namespace std; #define Maxsize 100 class LinearList{ public: LinearList() { last = -1; } //空表时last为-1 int data[Maxsize]; //申请表的空间 int last; //末端元素的下标 bool Isempty(LinearList *ptrl); //判断表是否为空 bool Isfull(LinearList *ptrl); //判断表是否为空 int length(LinearList *ptrl); //求表的长度 int GetElem(int i, LinearList *ptrl); //表中第i个位置的值 void Insert(int i, int x, LinearList *ptrl); //在第i个位置插入x void Delete(int i, LinearList *ptrl); //在第i个位置删除x int find(int x, LinearList *ptrl); //在表中查找x }; int main(){ int i, m; LinearList *ptrl = new LinearList; cout << "输入表的长度:" << endl; cin >> m; ptrl->last = m - 1; cout << "输入表的" << m << "个元素:" << endl; for (i = 0; i < ptrl->last + 1; i++) cin >> ptrl->data[i]; //----------------------------------------------------------- int l = ptrl->length(ptrl); cout << "表的长度为:" << l << endl; //------------------------------------------------------------ cout << "输入插入位置和元素;" << endl; cin >> i >> m; ptrl->Insert(i, m, ptrl); cout << "在第" << i << "个位置插入" << m << "后输出表:" << endl; for (i = 0; i < ptrl->last + 1; i++) cout << ptrl->data[i] << " "; cout << endl; //------------------------------------------------------------- cout << "输入删除的位置;" << endl; cin >> i; ptrl->Delete(i, ptrl); cout << "删除第" << i << "个元素,输出表:" << endl; for (i = 0; i < ptrl->last + 1; i++) cout << ptrl->data[i] << " "; cout << endl; //------------------------------------------------------------ cout << "输入要查找的数:" << endl; cin >> m; i = ptrl->find(m, ptrl); cout << "在表中查找" << m << endl; if (i == -1) cout << "没有查找到" << m << endl; else cout << m << "的下标为" << i << endl; //------------------------------------------------------------ return 0; } bool LinearList::Isempty(LinearList *ptrl){ if (ptrl->last == -1) return false; return true; } bool LinearList::Isfull(LinearList *ptrl){ if (ptrl->last == Maxsize - 1) return true; return false; } int LinearList::length(LinearList *ptrl){ return ptrl->last + 1; } int LinearList::GetElem(int i, LinearList *ptrl){ if (i<1 || i>ptrl->last + 1) cout << "输入位置不合理" << endl; else return ptrl->data[i - 1]; return 0; } void LinearList::Insert(int i, int x, LinearList *ptrl){ if (i<1 || i>ptrl->last + 1) cout << "插入位置不合理" << endl; else if (ptrl->last == Maxsize - 1) cout << "表已满,无法插入" << endl; else{ for (int j = ptrl->last; j >= i - 1; j--) ptrl->data[j + 1] = ptrl->data[j]; //从后面开始挪动 ptrl->data[i - 1] = x; //插入到第i个位置 ptrl->last++; //元素加1 } } void LinearList::Delete(int i, LinearList *ptrl){ if (i<1 || i>ptrl->last + 1) cout << "删除位置不合理" << endl; else{ for (int j = i - 1; j < ptrl->last; j++) ptrl->data[j] = ptrl->data[j + 1]; //从前面开始挪动 ptrl->last--; } } int LinearList::find(int x, LinearList *ptrl){ for (int i = 0; i < ptrl->last + 1; i++) if (x == ptrl->data[i]) return i; //找到就返回下标值 return -1; //否则返回-1 }