資料結構上機題(週三)
阿新 • • 發佈:2018-11-07
週三,19號的上機題。
題目,如圖:
不多廢話,直接原始碼:
#include<iostream> #include<stdlib.h> int a[100]; using namespace std; class node { public: node * next; int data; node() { next = NULL; data = 0; } }; class lnode{ node* head; public: lnode() { head = new node; }//1 ~lnode() {} void create();//2 void create2(int n,int a[]); void Print();//3 int del();//4 void delAll();//5 void rangedelte();//6 void f1();//7 void f2();//8 }; void lnode::create2(int n,int a[]) { node *p; for (int i = 0; i < n; i++) { p = new node; p->data=a[i]; p->next = head->next; head->next = p; } } void lnode::f2()// 上機題第二個; { cout << "刪除所有重複的數字:"<<endl; bool hashTable[1000] = { false }; node *q; node *p = head->next; while (p) { if (hashTable[p->data] == false) { hashTable[p->data] = true; q = p; p = p->next; } else { q->next = p->next; delete(p); p = q->next; } } } void lnode::f1()//上機題第一個; { cout << "分裂開奇偶數"; int i = 0; node *q = head; node *p = head->next; while (p) { if ((p->data) % 2 != 0) { a[i] = p->data; i++; q->next = p->next; delete(p); p = q->next; } else { q = p; p = p->next; } } lnode B; B.create2(i, a); cout << "偶數:"<<endl; Print(); cout << "奇數:"<<endl; B.Print(); } void lnode::rangedelte() { int min, max; cout << "在按值遞減的連結串列中進行區域刪除(刪除的值不包含min和max本身),依次輸入min與max的值:"; cin >> min >> max; node *pr = head, *p = head->next; while (p&&p->data <= min) { pr = p; p = p->next; } while (p&&p->data < max) { pr->next = p->next; delete(p); p = pr->next; } } void lnode::delAll() { int n; cout << "查詢是否存在該數,並刪除連結串列中所有的該數:"; cin >> n; node* q = head; node* p = q->next; while (p) { if (p->data != n) { q = p; p = p->next; } else { q->next = p->next; delete(p); p = q->next; } } } void lnode::create() { node *p; int n; cout << "輸入總個數:"; cin >> n; cout << "輸入值,請保持遞減:"; for (int i = 0; i < n; i++) { p = new node; cin >> p->data; p->next = head->next; head->next = p; } } void lnode::Print() { cout << "列印連結串列:"; node *p=head->next; while (p) { cout << p->data << ' '; p = p->next; } cout << endl; } int lnode::del() { int n; cout << "查詢是否存在該數,並刪除第一次出現的該數:"; cin >> n; int x=0; node* q = head; node* p = q->next; while (p) { if (p->data != n) { q = p; p = p->next; } else { q->next = p->next; delete(p); p = q->next; x = 1; goto loop; } } loop:; return x; } int main(void) { lnode A; A.create(); cout<<A.del()<<endl; A.Print(); A.delAll(); A.Print(); A.rangedelte(); A.Print(); A.f2(); A.Print(); A.f1(); system("pause"); return 0; }
下面是執行結果:
看完了,關注一下唄qwq