第三關挑戰題

#include<iostream>
#include<string>

typedef char ElemType;

struct SNode
{
	ElemType data;
	SNode* next;
};

void InitStack(SNode*& HS)
{
	HS = NULL;
}

void Push(SNode*& HS, const ElemType& item)
{
	SNode* newptr = new SNode;
	newptr->data = item;
	newptr->next = HS;
	HS = newptr;
}

ElemType Pop(SNode*& HS)
{
	if (HS == NULL)
	{
		std::cerr << "Linked stack is empty!" << std::endl;
		exit(1);
	}
	SNode* p = HS;
	HS = HS->next;
	ElemType temp = p->data;
	delete p;
	return temp;
}

ElemType Peek(SNode* HS)
{
	if (HS == NULL)
	{
		std::cerr << "Linked stack is empty!" << std::endl;
		exit(1);
	}
	return HS->data;
}

bool EmptyStack(SNode* HS)
{
	return HS == NULL;
}

void ClearStack(SNode*& HS)
{
	SNode *cp, *np;
	cp = HS;
	while (cp!=NULL)
	{
		np = cp->next;
		delete cp;
		cp = np;
	}
	HS = NULL;
}

void Transform(long num)
{
	SNode* a; int k;
	std::string ch = "123456789ABCDEF";
	InitStack(a);
	while (num != 0)
	{
		k = num % 16;
		Push(a, ch[k-1]);
		num = num / 16;

	}
	while (!EmptyStack(a))
		std::cout << Pop(a);
	std::cout << std::endl;
}

void main()
{
	long number;
	std::cout << "請輸入要轉化的十進制數字:";
	std::cin >> number;
	std::cout << "轉化後的16進制數字爲:";
	Transform(number);
	system("pause");
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章