线性表是n个具有相同类型的数据元素的有限序列。例如Array=(a1,a2,a3.......an);除a1和an其他元素都有一个前驱和一个后继,a1没有前驱,an没有后继。
我们可以用c++类实现:
#includeusing namespace std; const int Max = 100;//常量Max class SeqList { public: SeqList()//建立空的顺序表 { length = 0; } SeqList(int a[], int n);//以数组a[]为初始化数据建立一个长度为n的顺序表 ~SeqList(); void PushBack(int x);//尾部插入x int Length();//返回数组的长度 int Get(int i);//得到第i个位置的数 int Locate(int x);//返回这个数的索引 void Insert(int i, int x);//在i位置插入数字x void Delete(int i);//删除第i个数字 void PrintList();//打印链表 private: int data[Max];//存放数据元素的数组 int length;//顺序表的长度 }; SeqList::SeqList(int a[], int n) { if (n > Max) { cout << "参数非法" << endl; } for (int i = 0; i < n; i++) { data[i] = a[i]; } length = n; } int SeqList::Get(int i)//获取第i个位置的元素,这个i从1开始。 { if (i<1 || i>length) { cout << "输入错误" << endl; } return data[i - 1];//数组索引从0开始所以返回i-1; } int SeqList::Locate(int x)//返回x元素的索引。 { for (int i = 0; i < length; i++) { if (x == data[i]) { return i + 1; } } return 0; } void SeqList::Insert(int i, int x)//在i位置插入x { if (length > Max) cout << "顺序表已满" << endl; if (i<1 || i>length + 1) cout << "参数非法" << endl; for (int j = length - 1; j >= i - 1; j--) { data[j + 1] = data[j]; } data[i - 1] = x; length++; } void SeqList::Delete(int i)//删除第i个元素——也就是索引中i-1个元素 { if (length == 0) cout << "顺序表为空" << endl; if (i<1 || i>length) cout << "参数非法" << endl; int x = data[i - 1]; for (int j = i; j < length; j++) { data[j - 1] = data[j]; } length--; } void SeqList::PrintList() { cout << "打印数组中的数据" << endl; for (int i = 0; i < length; i++) { cout << data[i] << " "; } cout << endl; } SeqList::~SeqList() { } int SeqList::Length()//返回数组中元素的个数 { return length; } void SeqList::PushBack(int x)//数组尾部插入 { data[length] = x; length++; } void Merge(SeqList& L1, SeqList& L2, SeqList& L3)//合并两个数组 { int i = 1,j=1,k=1; int n1 = L1.Length(); int n2 = L2.Length(); while (i <= n1 && j <= n2) { if (L1.Get(i) <= L2.Get(j)) { L3.Insert(k, L1.Get(i)); i++; } else { L3.Insert(k, L2.Get(j)); j++; } k++; } while (i <= n1) { L3.Insert(k, L1.Get(i)); i++; k++; } while (j <= n2) { L3.Insert(k, L2.Get(j)); j++; k++; } } int main() { SeqList arr;//创建一个空数组 cout<<"数组为空"<< arr.Length() << endl; arr.PushBack(10); arr.PushBack(10); arr.PushBack(34); cout << "arr 的长度:" << arr.Length() << endl; cout << "打印arr数组" << endl; arr.PrintList(); arr.Insert(2, 4000); arr.PrintList(); SeqList arr1; SeqList arr2; arr1.PushBack(12); arr1.PushBack(10); arr1.PushBack(23); arr1.PushBack(45); Merge(arr, arr1, arr2);//合并arr和arr1到arr2中 arr2.PrintList(); return 0; }
哈哈,记得关注哦。



