栈的进制转换
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;
}