9.19 作业,用循环栈实现进制转换

头文件

#ifndef __SEQSTACK_H__
#define __SEQSTACK_H__
#define MAX 20
typedef int datatype;

typedef struct
{
	datatype data[MAX];
	int top;
}seqstack, *seqstack_po;

//创建
seqstack_po create();

//判空
int empty(seqstack_po s);

//判满
int full(seqstack_po s);

//入栈
int push(seqstack_po s,datatype e);

//出栈
int pop(seqstack_po s);

//遍历
void show(seqstack_po s);

//销毁
void my_free(seqstack_po s);

//进制转换
void transfor(seqstack_po s,int num,int value);

#endif

封装函数

 

#include "seqstack.h"
#include <stdlib.h>
#include <stdio.h>



//创建
seqstack_po create()
{
	seqstack_po s=(seqstack_po)malloc(sizeof(seqstack));
	if(NULL==s)
	{
		puts("Fail to create");
		return NULL;
	}
	s->top = -1;
	return s;
}

//判空
int empty(seqstack_po s)
{
	return s->top==-1;
}

//判满
int full(seqstack_po s)
{
	return s->top==MAX-1;
}

//入栈
int push(seqstack_po s,datatype e)
{
	if(NULL==s || full(s))
	{
		puts("Fail to push");
		return -1;
	}
	s->top++;
	s->data[s->top]=e;
	puts("Suc to push");
	return 0;
}

//出栈
int pop(seqstack_po s)
{
	if(NULL==s || empty(s))
	{
		puts("Fail to pop");
		return -1;
	}
	//datatype value=s->data[s->top];
	s->top--;
	//printf("输出 :%d\n",value);
	return 0;
}

//遍历
void show(seqstack_po s)
{
	if(NULL==s || empty(s))
	{
		puts("Fail to show");
		return;
	}
	printf("seqstack :");
	while(s->top!=-1)
	{
		printf("%d\t",s->data[s->top]);
		s->top--;
	}
	putchar(10);
}

//销毁
void my_free(seqstack_po s)
{
	if(NULL==s)
	{
		puts("Fail to free");
		return;
	}
	free(s);
	s=NULL;
	puts("Suc to free");
}

//进制转换
void transfor(seqstack_po s,int num,int value)
{
	int a,b;
	while(1)
	{
		a=num%value;
		b=num/value;
		num=b;
		push(s,a);
		if(b/value==0)
		{
			push(s,b);
			break;
		}
	}

}

主函数

#include "seqstack.h"
#include <stdlib.h>
#include <stdio.h>

int main(int argc, const char *argv[])
{
	seqstack_po s=create();
/*
	push(s,1);
	push(s,2);
	push(s,3);
	push(s,4);
	pop(s);
	show(s);
	my_free(s);
*/
	int num;
	printf("请输入一个数:");
	scanf("%d",&num);
	int value;
	printf("请输入想转变的进制数:");
	scanf("%d",&value);
	transfor(s,num,value);
	show(s);
	my_free(s);
	s=NULL;
	show(s);
	return 0;
}

 现象

请输入一个数:15
请输入想转变的进制数:2
Suc to push
Suc to push
Suc to push
Suc to push
seqstack :1	1	1	1	
Suc to free
Fail to show
ubuntu@ubuntu:~/whp/9_month/seqstack$ ./a.out 
请输入一个数:75
请输入想转变的进制数:8
Suc to push
Suc to push
Suc to push
seqstack :1	1	3	
Suc to free
Fail to show

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值