数据结构作业

栈的进制转换

1、head.h

#ifndef __HEAD_
#define __HEAD_
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef int datatype;
typedef struct Node 
{
	union
	{
		int len;
		datatype data;
	};
	struct Node *next;
}*linkstrak;
linkstrak create_head();
linkstrak create_node();
int input(linkstrak top ,datatype e);
void output(linkstrak top);
int delete(linkstrak top);
linkstrak free_all(linkstrak top);
int shift(linkstrak top,int num);
#endif

2、main.c

#include"head.h"


int main(int argc, const char *argv[])
{
	linkstrak top=create_head();
	int num;
	printf("请输入十进制的数:");
	scanf("%d",&num);
	shift(top,num);
	top=free_all(top);
	return 0;
}

3、test.c

#include"head.h"
linkstrak create_head()
{
	linkstrak top=(linkstrak)malloc(sizeof(struct Node));
	if(top==NULL)
		return NULL;
	top->len=0;
	top->next=NULL;
	return top;
}
linkstrak create_node()
{
	linkstrak p=(linkstrak)malloc(sizeof(struct Node));
	if(p==NULL)
		return NULL;
	p->len=0;
	p->next=NULL;
	return p;
}
int input(linkstrak top ,datatype e)
{
	if(top==NULL)
	{
		printf("插入失败\n");
		return -1;
	}
	linkstrak s=create_node();
	if(s==NULL)
		return -1;
	s->data=e;
	s->next=top->next;
	top->next=s;
	top->len++;
	return 0;
}
void output(linkstrak top)
{
	if(top==NULL)
	{
		printf("遍历失败\n");
		return ;
	}
	puts("\n");
	linkstrak p=top;
	printf("其对应的二进制为:");
	while(p->next!=NULL)
	{
		p=p->next;
		printf("%d\t",p->data);
	}
	puts("\n");
}
int delete(linkstrak top)
{
	if(top==NULL||top->len==0)
	{
		printf("删除失败\n");
		return -1;
	}
	linkstrak p=top->next;
	printf("出栈的元素为:%d\t",p->data);
	top->next=p->next;
	free(p);
	p=NULL;
	top->len--;
	puts("\n");
	return 0;
}
linkstrak free_all(linkstrak top)
{
	if(top==NULL)
		return NULL;
	int n=top->len;
	for(int i=0;i<n;i++)
	{
		delete(top);
	}
	free(top);
	top=NULL;
	return top;
}
int shift(linkstrak top,int num)
{
	if(top==NULL)
	{
		printf("转换失败\n");
		return -1;
	}
	while(num>0)
	{
		input(top,num%2);
		num/=2;
	}
	output(top);
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值