1.c
#include "head.h"
/*
* function: 创建头节点
* @param [ in] 无参数
* @param [out]
* @return 成功返回地址 失败返回NULL
*/
linkstack creat_head()
{
linkstack top=(linkstack)malloc(sizeof(struct Node));
if(top==NULL)
return NULL;
top->len=0;
top->next=NULL;
return top;
}
/*
* function: 创建普通节点
* @param [ in] 无参数
* @param [out]
* @return 成功返回地址 失败返回NULL
*/
linkstack creat_node()
{
linkstack p=(linkstack)malloc(sizeof(struct Node));
if(p==NULL)
return NULL;
p->data=0;
p->next=NULL;
return p;
}
/*
* function: 链栈的入栈
* @param [ in] 栈 插入的值
* @param [out]
* @return 成功返回0 失败返回-1
*/
int linkstack_push(linkstack top,datatype e)
{
//判断栈是否存在
if(top==NULL)
{
printf("头插失败\n");
return -1;
}
//插入新结点s
linkstack s=creat_node();
if(s==NULL)
return -1;
//s的数据域
s->data=e;
//s的指针域
s->next=top->next;
top->next=s;
top->len++;
return 0;
}
/*
* function: 链栈的出栈
* @param [ in] 链栈
* @param [out]
* @return 成功返回0 失败返回-1
*/
int linkstack_pop(linkstack top)
{
//判断栈是否存在
//判断栈是否为空
if(top==NULL||top->len==0)
{
printf("删除失败\n");
return -1;
}
//删除
linkstack q=top->next;
printf("出栈的元素是:%d\n",q->data);
top->next=q->next;
free(q);
q=NULL;
top->len--;
return 0;
}
/*
* function: 链栈遍历
* @param [ in] 链栈
* @param [out]
* @return 无返回值函数
*/
void linkstack_output(linkstack top)
{
puts("");
linkstack p=top;
while(p->next!=NULL)
{
p=p->next;
printf("%d\t",p->data);
}
puts("");
}
/*
* function: 改变进制输出
* @param [ in] 链栈
* @param [out]
* @return 成功返回0 失败返回-1
*/
int linkstack_change(linkstack top,datatype n)
{
linkstack p=top;
while(n>0)
{
linkstack_push(top,n%2);
n/=2;
}
}
/*
* function: 链栈的空间释放
* @param [ in] 链栈
* @param [out]
* @return 返回NULL
*/
linkstack linkstack_free(linkstack top)
{
if(top==NULL)
return NULL;
int n=top->len;
for(int i=0;i<n;i++)
{
linkstack_pop(top);
}
free(top);
top=NULL;
return top;
}
main.c
#include "head.h"
int main(int argc, const char *argv[])
{
//创建链栈
linkstack top=creat_head();
#if 0 //入栈
char choice[10];
datatype e;
while(1)
{
printf("请输入您要入栈的数据元素:");
scanf("%d",&e);
linkstack_push(top,e);
printf("您要继续吗?yes/no:");
scanf("%s",choice);
if(strcmp(choice,"no")==0)
{
break;
}
}
//遍历
linkstack_output(top);
//出栈
linkstack_pop(top);
linkstack_output(top);
#else
int n;
printf("输入一个数:");
scanf("%d",&n);
linkstack_change(top,n);
linkstack_output(top);
int m=top->len;
for(int i=0;i<m;i++)
linkstack_pop(top);
#endif
return 0;
}
head.h
#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 creat_head();
linkstack creat_node();
int linkstack_push(linkstack top,datatype e);
int linkstack_pop(linkstack top);
void linkstack_output(linkstack top);
linkstack linkstack_free(linkstack top);
int linkstack_change(linkstack top,datatype n);
#endif