线性表的数组实现
rt,谢谢!
/* 线性表-数组实现: Author:Deny 于 2016.6.29 */ #include <cstdio> #include <iostream> #include <cstring> #define Print() cout << "id out of bounds!" << endl; #define Size 10005 using namespace std; class list{ private: int tail,Arr[Size]; public: void clear(){ tail = 0; memset(Arr,0,sizeof(Arr)); } bool isEmpty(){ return tail == 0; } int size(){ return tail; } int getElement(int id){ return Arr[id]; } int FindElement(int x){ for(int i = 0; i < tail; i++) if(Arr[i] == x) return i; return -1; } void Insert(int id,int x){ if(id > tail){ Print(); return ; } for(int i = tail; i > id; i--) Arr[i] = Arr[i-1]; Arr[id] = x; tail++; } void Delete(int id){ if(id >= tail){ Print(); return ; } for(int i = id+1; i < tail; i++) Arr[i-1] = Arr[i]; tail--; } void Tra(){ if(!tail){ cout << "The link is empty!" << endl; return ; } for(int i = 0; i < tail; i++) cout << Arr[i] << " "; cout << endl; } list(){ tail = 0; memset(Arr,0,sizeof(Arr)); } }; //order = -1 时退出,order = 1 时清空线性表,order = 2时判断线性表是否为空 //order = 3 时输出线性表的长度 ,order = 4时还需输入 id 输出 Arr[id] //order = 5 时还需输出 num 判断 num 是否在 Arr[] 数组中,order = 6 时还需输入 id 和 num,把 num 插入 到 id 位 //order = 7 时还需输出 id 删除 Arr[id], order = 8时遍历 Arr[] int main(){ int order; list k; cout << "Input order:"; while(cin >> order){ if(order == -1) break; else if(order == 1) k.clear(); else if(order == 2){ k.isEmpty()?cout << "The link is empty." << endl:cout << "The link isn't empty." << endl; } else if(order == 3) cout << k.size() << endl; else if(order == 4){ int x; cin >> x; cout << k.getElement(x) << endl; } else if(order == 5){ int num,q; cin >> num; q = k.FindElement(num); q == -1?cout << "Not Found!" << endl:cout << "It's in id " << q << " ." << endl; }else if(order == 6){ int id,num; cin >> id >> num; k.Insert(id,num); } else if(order == 7){ int id; cin >> id; k.Delete(id); } else if(order == 8){ k.Tra(); } else cout << "Input error!" << endl; cout << "Input order:"; } return 0; }
举报