/******************************** * * c++程序設計實踐指導 * * 1.3求任意整數降序數 * *********************************/ #include <iostream> using namespace std; class NUM { struct LinkNode { int key; LinkNode *Next; }; long long n; //存放整數 LinkNode *head; //單鏈表表頭節點 public: NUM(long long x) //構造函數,用x初始化n; { n = x; int w = 0; while(n) { n = n / 10; ++w; } head = new LinkNode; LinkNode *p = head; p->key = 0; for(int i = 0; i < w-1; i++) { LinkNode *q = new LinkNode; q->key = 0; p->Next = q; p = q; } p->Next = NULL; n = x; } void decrease(); //完成降序排列的功能 void expect(); //按最大、最小、次最大、次最小等間隔排列 void show() //在屏幕顯示功能 { int sumn = 0; LinkNode *p = head; cout << "the number is : " << n << endl; cout << "we change it to : "; while(p) { cout << p->key; sumn += p->key; p = p->Next; } cout << endl; cout << "Sum of every number is :" << sumn << endl; } }; void NUM::decrease() //降序 { long long k; //k存放整數值 int temp; //臨時存放替換元素值 k = n; LinkNode *p = head; while(p) //將整數分解存入單鏈表中 { p->key = k % 10; k = k / 10; p = p->Next; } p = head; while(p->Next) //新建指針q爲p的下指針位置,比較p和q的鍵值,指針q依次向後移,完了以後p後移一位,q爲p的下指針位置 { LinkNode *q = new LinkNode; q = p->Next; while(q) { if(q->key > p->key) //大的鍵值前移 { temp = q->key; q->key = p->key; p->key = temp; } q = q->Next; } p = p->Next; q = p->Next; } } void NUM::expect() //最大、最小、次最大、次最小的順序 { long long k; //k存放整數值 int temp; //臨時存放替換元素值 k = n; LinkNode *p = head; while(p) //將整數分解存入單鏈表中 { p->key = k % 10; k = k / 10; p = p->Next; } p = head; LinkNode *q = new LinkNode; while(p->Next && p->Next->Next) { q = p->Next; while(q) //p指針後最大的鍵值前移 { if(q->key > p->key) { temp = q->key; q->key = p->key; p->key = temp; } q = q->Next; } p = p->Next; q = p->Next; while(q) //p指針後最小的鍵值前移 { if(q->key < p->key) { temp = q->key; q->key = p->key; p->key = temp; } q = q->Next; } p = p->Next; q = p->Next; } if(p->Next) //結束前判斷是否剩餘一對鍵值爲比較 { if(q->key > p->key) { temp = q->key; q->key = p->key; p->key = temp; } } } int main() { long long m; cout << "please enter some number : " << endl; cin >> m; cout << endl; NUM nx(m); nx.decrease(); nx.show(); cout << endl; nx.expect(); nx.show(); system("pause"); return 0; }