1.3 求任意整数降序数

/********************************
*
*		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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值