/*動態數組 使用鏈表實現*/ #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; void menu(); template <class T> class Link_Array { typedef struct node { T data; struct node*next; }Node; public: Link_Array() { length = 0; head = NULL; temp = NULL; } void input()//數組中元素的輸出 { Node*pr = head; cout<<"當前數組中共有"<<length<<"個元素"<<endl; cout<<"數組中的元素有:"; while(pr != NULL) { cout<<pr->data<<"->"; pr = pr->next; } cout<<"NULL"; } void add()//添加元素 { T num; Node*pr = NULL; cout<<"請輸入你要添加的元素:"; cin>>num; pr = new Node; pr->data = num; if(head == NULL)head = pr; else temp->next = pr; temp = pr; temp->next = NULL; length++; cout<<"元素插入成功!!!"<<endl; } void del()//刪除元素 { int position,counter = 0; Node*pr = head,*p = NULL; cout<<"請輸入元素的位置編號(1-"<<length<<"),以便於做刪除操作."; cin>>position; if(position < 1 || position > length)cout<<"你輸入的位置不存在!!!"<<endl; else { while(counter <= position-1) { p = pr; pr = pr->next; counter++; } p->next = pr->next; delete pr; } cout<<"元素刪除成功!!!"<<endl; } void change()//按照位置修改元素 { Node*pr = head; int position,num,counter = 0; cout<<"請輸入元素的位置編號(1-"<<length<<"),以便於做修改操作."; cin>>position; if(position < 1 || position > length)cout<<"你輸入的位置不存在!!!"<<endl; else { cout<<"請輸入修改后的數字:"; cin>>num; while(counter < position-1) { pr = pr->next; counter++; } pr->data = num; cout<<"元素修改成功!!!"<<endl; } } void insert()//插入元素 { Node*pr = head,*p = NULL; int position,num,counter = 1; cout<<"請輸入元素的位置編號(1-"<<length<<"),以便於做插入操作."; cin>>position; cout<<"請輸入插入元素的元素值:"; cin>>num; if(position < 1 || position > length)cout<<"你輸入的位置不存在!!!"<<endl; else { p = new Node; p->data = num; while(counter < position-1) { pr = pr->next; counter++; } p->next = pr->next; pr->next = p; cout<<"元素插入成功!!!"<<endl; } } void main1(Link_Array arr) { int ch; menu(); while(1) { cout<<"請輸入你的選項"; cin>>ch; if(ch==6) { exit(0); } else { switch (ch) { case 1: arr.add(); break; case 2: arr.del(); break; case 3: arr.change(); break; case 4: arr.insert(); break; case 5: arr.input(); break; } } } } private: int length = 0; struct node*head; struct node*temp; }; void menu() { cout<<"1. 添加元素 "<<endl; cout<<"2. 刪除元素 "<<endl; cout<<"3. 修改元素 "<<endl; cout<<"4. 插入元素 "<<endl; cout<<"5. 輸出元素 "<<endl; cout<<"6. 退出系統 "<<endl; } int main() { int x; Link_Array<int> arr; Link_Array<char> arr2; Link_Array<double> arr3; Link_Array<string> arr4; printf("請你個用戶選擇鏈表元素的類型:\n1.整型 \n2.字符型 \n3.浮點型 \n4.字符串"); scanf("%d",&x); switch(x) { case 1: arr.main1(arr); break; case 2: arr2.main1(arr2); break; case 3: arr3.main1(arr3); break; case 4: arr4.main1(arr4); break; } return 0; }
將原來的對動態數組的操作改為了對鏈表的操作,省去了數組空間的擴充,還有減掉了對數組運算符重載的使用,。
使用到了數據結構中的鏈表,C++中的類模板,大概就是這樣吧。
主要的是當我將鏈表節點的結構體放入類class Link_Array的時候我的類模板T一下子就可以對鏈表節點中的data數據類型進行改寫了,這實在是有點爽哦。
主要還是不知道具體老師讓寫的題目具體是什么,總之,在多態和虛函數中沒有在代碼中體現出來,這就有點惱火。
嗨呀,加油吧!!!