数据结构栈应用之进制转换

#include<stdio.h>
#include<stdlib.h>
typedef int Elem;
typedef int Status;
#define ERROR 0
#define OK 1
typedef struct Node
{
	char elem;
	Node *next;
}Node,*Sqstack;
Sqstack top = NULL;           //链栈规定唯一的栈顶top

Status Push(Sqstack &top,Elem a)
{
	Sqstack l = (Sqstack)malloc(sizeof(Node));
	l->elem = a;
	l->next = top;        //将元素压入栈中
	top = l;              //移动指针
	return OK;
}

Status Pop(Sqstack &top,Elem &e)    //弹出栈顶元素  返回弹出值
{
	if(!top)
		return ERROR;
	Sqstack l = (Sqstack)malloc(sizeof(Node));
	l = top;
	e = l->elem;
	top = top->next;
	free(l);
	return OK;

}

Status GetTop(Sqstack top,Elem &e)//取栈顶元素值如果为空返回ERROR否则返回栈顶元素 OK
{
	if(!top)
		return ERROR;
	else
	{
		e = top->elem;
		return OK;
	}
}
//括号匹配
/*
int main()
{
	char s[1000];
	printf("输入你需要匹配的表达式:");
	gets(s);
	int i = 0;
	while(s[i]!='\0')
	{
		if(s[i]=='(')
			Push(top,s[i]);
		if(s[i]==')')
		{
			if(top == NULL)
			{
				printf("匹配失败!\n");
				getchar();
				getchar();
				return 0;
			}
			Pop(top,s[i]);
		}
		i++;
	}
	char a;
	if(GetTop(top,a))
		printf("匹配失败!\n");
	else
		printf("匹配成功!\n");
	getchar();
	getchar();
	return 0;
}*/

void conversion()
{
	int n; //用来存放输入进去的数组
	scanf("%d",&n);
	while(n)    //当n的值不为零时
	{
		Push(top,n%2);
		n = n/2;   //将n缩小
	}
	int e;       //用来存储
	while(Pop(top,e))
	{
		printf("%d",e);
	}
	printf("\n");
}

//禁止转换
int main()
{
	conversion();
	getchar();
	getchar();
}

重要代码

<span style="background-color: rgb(255, 0, 0);"><span style="font-size:24px;">	while(n)    //当n的值不为零时
	{
		Push(top,n%2);                         将取余二的值压入栈中
		n = n/2;   //将n缩小                   倒叙输出
	}</span></span>
 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值