欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言实现用链栈完成十进制转二进制

程序员文章站 2022-03-08 15:52:47
...
#include <stdio.h>
#include <stdlib.h>


#define MAX 100
#define OK 1
#define ERROR -1
#define STACK_SIZE 100 

typedef int Elemtype;

Elemtype number;

//链栈的节点描述 
struct list_stack
{
	Elemtype datanum;
	struct list_stack *next;
} ;

typedef struct list_stack node;
typedef node *link;


//初始化栈 
link stack=NULL;

//进栈
link push(link stack,Elemtype data) 
{
	link newpointer;
	
	newpointer=(link)malloc(sizeof(node));
	
	if(newpointer==NULL)
	{
		printf("\n****ERROR****\n");
		exit(ERROR);
	}
	else
	{
		newpointer->datanum=data;
		newpointer->next=stack;
		stack=newpointer;
	}
	
	return stack;
	
	
}

//出栈,返回栈顶节点的指针,并把栈顶节点的值赋给全局变量number 
link pop(link stack)
{
	link pointer;
	pointer=stack;
	
	if(stack==NULL)
	{
		
		printf("\n---Empty---\n");
	}
	else
	{
		number=stack->datanum;
		stack=stack->next;
		free(pointer);
	}
	
	return stack;
	
}

//打印栈
void printf_list_stack(link stack)
{
	link pointer;
	
	pointer=stack;
	
	printf("输出该数的二进制:");
	
	
	if(pointer==NULL)
	{
		printf("---Empty---\n");
	}
	
	
	while(pointer!=NULL)
	{
		printf(" %d ",pointer->datanum);
		pointer=pointer->next;
	}
	
} 

//销毁栈 
void free_stack(link stack)
{
	link pointer;
	
	while(stack!=NULL)
	{
	   pointer=stack;
	   stack=pointer->next;
	   free(pointer);	
	}
}

void ten_change_two(Elemtype temp)
{
	Elemtype shang=1,yu;
	
	while(1)
	{
		if(shang==0)
		  break;
		
		
		shang=temp/2;
		yu=temp%2;
		stack=push(stack,yu);
		temp=shang;  
	}
	
	
	
}

int main(int argc, char *argv[])
{
	
	
	Elemtype temp;
	
	printf("Enter a number:");
	scanf("%d",&temp);
	
	ten_change_two(temp);
	
	printf_list_stack(stack);
	printf("\n");

    free(stack); 
    printf("\n");
	printf("****感谢您的使用****"); 
    printf("\n");
	
	return 0;
}