头文件
#ifndef __HEAD_H__
#define __HEAD_H__#include<stdio.h>
#include<string.h>
#include<stdlib.h>typedef int datatype;
typedef struct Node
{
union
{
int len;
datatype data;
};
struct Node *next;
}*linkstack;
linkstack create(int flag);
int linkstack_push(linkstack stack, datatype e);
void output(linkstack stack);
linkstack free_space(linkstack stack);
#endif
自定义文件
#include "head.h"
/*
* function: 创建结点
* @param [ in]
* @param [out]
* @return 成功返回地址 失败返回NULL
*/
linkstack create(int flag)
{
linkstack top = (linkstack)malloc(sizeof(struct Node));
if(top == NULL)
return NULL;
switch(flag)
{
case 1:
top->len = 0;
top->next = NULL;
break;
case 2:
top->data = 0;
top->next = NULL;
}
}/*
* function: 入栈
* @param [ in]
* @param [out]
* @return 成功返回0 失败返回-1
*/int linkstack_push(linkstack stack, datatype e)
{
if(stack == NULL)
{
printf("头插失败\n");
return -1;
}
linkstack s = create(2);//创建新结点
if(s == NULL)
return -1;
//数据域
s->data = e;
//指针域
s->next = stack->next;
stack->next = s;
stack->len++;
return 0;
}
/*
* function: 出栈
* @param [ in] 链栈
* @param [out]
* @return
*/int linkstack_pop(linkstack stack)
{
if(stack == NULL || stack->len ==0)
{
printf("头删失败\n");
return -1;
}
linkstack p = stack->next;
stack->next = p->next;
free(p);
p = NULL;
stack->len--;
return 0;
}/*
* function: 链栈遍历
* @param [ in]
* @param [out]
* @return 无返回值
*/void output(linkstack stack)
{
if(stack == NULL || stack->len == 0)
{
printf("遍历失败\n");
return ;
}
linkstack p = stack;
puts("");
while(p->next)
{
p = p->next;
printf("%d",p->data);
}
puts("");
}
/*
* function: 释放空间
* @param [ in]
* @param [out]
* @return
*/linkstack free_space(linkstack stack)
{
if(stack == NULL)
return NULL;
int n = stack->len;
for(int i = 0; i < n; i++)
linkstack_pop(stack);
free(stack);
stack = NULL;
return stack;
}
主函数文件
#include "head.h"
int main (int argc, const char *argv[])
{
int num;
datatype e;
linkstack top = create(1);//创建头结点
printf("请输入您要转换的数\n");
scanf("%d",&num);
while(num)
{
datatype e = num % 2;
//入栈
linkstack_push(top,e);
num/= 2;
}
output(top);
//释放
top = free_space(top);
return 0;
}