链式栈进制转换

//链式栈 
#include<stdio.h>
#include<malloc.h>

struct node {
	int data;
	struct node *next;
}; 

void in_stack(struct node *top,int x)			//入栈 
{
	struct node *p;
	while(x!=0)
	{
		p=(struct node *)malloc(sizeof(struct node));		//产生节点 
		p->data=x%2;
		x=x/2;
		p->next=top->next;
		top->next=p;
		
	 } 
		
}

void out_stack(struct node *top)			//出栈 
{
	struct node *q;
	while(top->next!=NULL)				//当top->next为空时结束,说明都已经出栈 
	{
		q=top->next;					//保留出栈的元素 
		printf("%d",q->data);			//输出 
		top->next=q->next;
		free(q);						//释放出栈元素 
	}	
} 

void main()
{
	struct node *top;									//定义结构指针变量 
	top=(struct node *)malloc(sizeof(struct node));						//开辟空间 
	top->next=NULL;
	int x;
	printf("\n输入十进制数:");
	scanf("%d",&x);
	printf("\n->%d-输入数的十进制数对应的二进制数:",x);
	in_stack(top,x);
	out_stack(top);
	
}

 

posted @ 2019-09-29 09:48  JackieDYH  阅读(6)  评论(0编辑  收藏  举报  来源