码迷,mamicode.com
首页 > 其他好文 > 详细

浅谈栈&&进制转换

时间:2015-05-08 09:33:28      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:   typedef   

利用stack实现进制转换


Stack.h

#ifndef _STACK_H_
#define _STACK_H_

#include<iostream>
#include<assert.h>
using namespace std;

typedef int ElemType;

#define STACK_MAX_SIZE 100
#define HEX            2

typedef struct Stack
{
	ElemType *base;//栈底指针
	int top;       //栈顶标识
	int stacksize; //当前入栈元素个数
	int capacity;  //最大容量
}Stack;

void InitStack(Stack *stack);//初始化stack
bool isfull(Stack *stack);//判断stack是否为满
bool isempty(Stack *stack);//<span style="font-size: 12.6315793991089px; font-family: Arial, Helvetica, sans-serif;">判断stack是否为空</span>
bool push(Stack *stack,ElemType x);//入stack
//int pop(Stack *stack);
bool show_stack(Stack *stack);//打印
void clear(Stack *stack);//清空
void destroy(Stack *stack);//销毁
void Pop(Stack *stack,ElemType *e);//弹stack,并返回stack顶元素


#endif //_STACK_H_
<span style="font-family:Arial, Helvetica, sans-serif;font-size:24px;color:#ff0000;">stack.cpp</span>
<pre name="code" class="cpp">#include"Stack.h"


void InitStack(Stack *stack)
{
	stack->base = (ElemType *)malloc(sizeof(ElemType)*STACK_MAX_SIZE);
	assert(stack->base != NULL);
	stack->top = 0;
	stack->capacity = STACK_MAX_SIZE;
	stack->stacksize = 0;
}

bool isfull(Stack *stack)
{
	return stack->stacksize == stack->capacity;
}

bool isempty(Stack *stack)
{
	return stack->stacksize == 0;
}

bool push(Stack *stack,ElemType x)
{
	if(isfull(stack))
		return false;

	stack->base[stack->top++] = x;
	stack->stacksize++;
	return true;
}

void Pop(Stack *st,ElemType *e)
{
	if(isempty(st))
	{
		cout<<"栈以空,不能出栈!"<<endl;
	}
	--(st->top);
	*e = st->base[st->top];
	st->stacksize--;
}

/*
bool pop(Stack *stack)
{
	if(isempty(stack))
		return false;
	stack->base[stack->top--];
	return true;

}*/


ElemType GetTop(Stack *stack,ElemType *x)
{
	if(isempty(stack))
	{
		cout<<"栈空!"<<endl;
	}

	return stack->base[stack->stacksize-1];
}

bool show_stack(Stack *stack)
{
	if(isempty(stack))
		return false;
	for(int i = stack->top-1;i>=0;--i)
		cout<<stack->base[i]<<endl;
	return true;
}

void clear(Stack *stack)
{
	stack->top = 0;
}

void destroy(Stack *stack)
{
	clear(stack);
	free(stack->base);
	stack->capacity = 0;
	stack->stacksize = 0;
}


main.cpp

#include"Stack.h"

void conversion(int n)
{
	Stack mystack;
	int m;
	InitStack(&mystack);
	while(n)
	{
		push(&mystack,n%HEX);
		n = n / HEX;
	}
	while(!isempty(&mystack))
	{
	//	show_stack(&mystack);
	//	mystack.top = 0;
		Pop(&mystack,&m);
		cout<<m;
	}
	cout<<endl;

}

void main()
{
	int n = 25555;
	cout<<n<<" conversion "<<HEX<<" hex is ";
	conversion(n);
}

技术分享

浅谈栈&&进制转换

标签:   typedef   

原文地址:http://blog.csdn.net/chenmengmengx/article/details/45568325

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!