/********************************
*
* 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;
}
转载于:https://my.oschina.net/u/862938/blog/111577