二进制转换


```c
#include<stdio.h>
#include<stdlib.h>
#define max_stacks 10
//二进制转换
#define MALLOC(p,s)\
if(!((p)=(stackPointer)malloc(s))){\
fprintf(stderr,"Insufficient memory");\
exit(EXIT_FAILURE);\
}

typedef struct{
	int key;
}element;
typedef struct stack *stackPointer;
typedef struct stack{
	element data;
	stackPointer link;
};
int i;
void Create(int i);
int isEmpty(int i);
int isFull(int i);
void push(int i,element item); 
element pop(int i);
stackPointer top[max_stacks];


void Create(int i){
	top[i]=NULL;
}

int isEmpty(int i){
	return top[i]==NULL;
}

int isFull(int i){
	return 0;
}

void push(int i,element item){
	stackPointer temp;
	MALLOC(temp,sizeof(*temp));
	temp->data=item;
	temp->link=top[i];
	top[i]=temp;
}

element stackEmpty(){
	element item;
	item.key=-1;
	return item;
}

element pop(int i){
	stackPointer temp=top[i];
	element item;
	if(isEmpty(i)) return stackEmpty();
	item=temp->data;
	top[i]=temp->link;
	free(temp);
	return item;
}

void convert(int decimal){
	int yushu;
	element item;
	Create(0);
	while(decimal>0){
		yushu=decimal%2;
		decimal/=2;
		item.key=yushu;
		push(0,item);	
	}
	printf("二进制:");
	while(!isEmpty(0)){
		item=pop(0);
		printf("%d",item.key);
	}
	printf("\n");
}

int main(void){
	int decimal;
	printf("输入十进制数:\n");
	scanf("%d",&decimal);
	while(decimal!=-1){
		convert(decimal);
		printf("输入十进制数\n");
		scanf("%d",&decimal);
	}
	printf("Bye");
}```

#include<stdio.h>
#include<stdlib.h>
//二进制转换 
typedef struct node *stack;
struct node{
	int data;
	stack next;
};
stack makestack(){
	stack head=(stack)malloc(sizeof(struct stack));
	head->next=NULL;
	return head;
}
int push(stack head,int x) {
	stack newnode=(stack)malloc(sizeof(struct stack));
	newnode->data=x;
	newnode->next=head->next;
	head->next=newnode;
}
int pop(stack head){
stack temp=(stack)malloc(sizeof(struct node));
temp=head->next;
int tmp=head->next->data;
head->next=temp->next;
free(tmp);
return tmp;
}
int main(void){
	stack head = makestack();
	while(n!=0){
		push(head,n%2);
		n/=2;
	}
	while(head->next!=NULL){
		printf("%d",pop(head));
		if(head->next==NULL) 
		printf("\n");
	}
	return 0;
}```

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值