#include <iostream>
using namespace std;
const int MaxSize = 100;
template <typename T>
class SeqList {
public:
SeqList();
SeqList(T a[], int n);
~SeqList();
int Length();
T Get(int i);
int Locate(T x);
void Insert(int i, T x);
T Delete(int i);
void Empty();
void PrintList();
private:
T data[MaxSize];
int length;
};
template <typename T>
SeqList<typename T>::SeqList(T a[], int n) {
if (n > MaxSize) throw "參數(shù)非法";
length = n;
for (int i = 0; i < n; i++) {
data[i] = a[i];
}
}
template <typename T>
SeqList<typename T>::SeqList():length(0){}
template <typename T>
SeqList<typename T>::~SeqList(){}
template <typename T>
int SeqList<typename T>::Length() {
return length;
}
template <typename T>
T SeqList<typename T>::Get(int i) {
return data[i - 1];
}
template <typename T>
int SeqList<typename T>::Locate(T x) {
for (int i = 0; i < length; i++) {
if (data[i] == x) {
return i+1;
}
}
}
template <typename T>
void SeqList<typename T>::Insert(int i, T x) {
if (length == MaxSize) {
throw "上溢";
}
if (i<1 || i>length + 1) {
throw "插入位置非法";
}
for (int j = length; j >= i; j--) {
data[j] = data[j - 1];
}
data[i - 1] = x;
length ++;
}
template <typename T>
T SeqList<typename T>::Delete(int i) {
T x;
if (length == 0) {
throw "下溢";
}
x = data[i - 1];
if (i<1 || i>length) {
throw "刪除位置錯(cuò)誤";
}
for (int j = i; j < length; j++) {
data[j - 1] = data[j];
}
length--;
return x;
}
template <typename T>
void SeqList<T>::Empty() {
if (length == 0) {
cout << "是空表" << endl;
}
else {
cout << "不是空表" << endl;
}
}
template <typename T>
void SeqList<T>::PrintList() {
if (length == 0) {
cout << "empty list" << endl;
}
else {
for (int i = 0; i < length; i++) {
cout << data[i] << "\t";
}
cout << endl;
}
}
int main(){
int a[] = { 1,2,3,4,5 };
//SeqList<int> q1 = { a, 5 };
SeqList<int> q1(a,5);
q1.PrintList();
q1.Empty();
cout<<"the second element is:"<<q1.Get(2)<<endl;
cout<<"length of the list is:"<<q1.Length()<<endl;
cout <<"the location 4 of is:"<< q1.Locate(4) << endl;
q1.Insert(2, 8);
q1.PrintList();
q1.Delete(4);
q1.PrintList();
SeqList<int> q2;
q2.PrintList();
return 0;
}
順序表 C++
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- Output: 只有一層循環(huán),循環(huán)次數(shù)為L(zhǎng)c.length時(shí)間復(fù)雜度為Ο(La.length+Lb.length)。
- 一、順序表基礎(chǔ)概念講解 所謂的順序表,也就是,想對(duì)于那種所謂的鏈表存儲(chǔ),我們可以從第一個(gè)節(jié)點(diǎn),就可以通過(guò)地址的移動(dòng)...