#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>