数据结构——栈的动态实现(malloc/free)(C语言实现)

/*************************************************************************
    > File Name: stack.c
    > Author: Andy001847
    > Mail: yunzhonglai@hotmail.com 
    > Created Time: 2014年10月21日 星期二 22时50分07秒
 ************************************************************************/


//栈的链式实现


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


typedef struct node{
int data;               //数据域
struct node *p_next;    //下一节点的存储位置
}node;


static node head, tail;     //虚构头尾节点


//初始化栈
void init(){
head.p_next = &tail;
}


//清理栈
void deinit(){
while(head.p_next != &tail){
node *p_node = head.p_next;
head.p_next = head.p_next -> p_next;
free(p_node);
p_node = NULL;
}
}


//判栈空
int empty(){
return head.p_next == &tail;
}


//判栈满
int full(){
return 0;   //链栈不会满,除非内存不足
}


//入栈
void push(int num){
node *p_node = (node *)malloc(sizeof(node));
if(!p_node){
perror("malloc");
return;
}
p_node -> data = num;             //将要入栈的数值给新节点
p_node -> p_next = head.p_next;   //将新节点挂在头节点后面
head.p_next = p_node;             //将新节点挂在头节点后面
}


//出栈
int pop(){
int num = 0;
if(head.p_next != &tail){
node *p_node = head.p_next;
num = head.p_next -> data;
head.p_next = head.p_next -> p_next;
free(p_node);
p_node = NULL;
}
return num;
}


//取栈顶元素
int top(){
return (head.p_next == &tail) ? 0 : (head.p_next -> data);
}


//读取栈中有效数据个数
int size(){
int cnt = 0;
node *p_node = NULL;
for(p_node = &head; p_node != &tail; p_node = p_node -> p_next){
node *p_lnext = p_node -> p_next;
if(p_lnext != &tail){
cnt++;
}
}
return cnt;
}


int main(void){
init();     //初始化栈


char choice = 'y';
//入栈
do{
int num = 0;
printf("请输入一个整数:");
//差错处理
while(!scanf("%d",&num)){
scanf("%*[^\n]");   //清除缓冲区中的非法换行符
scanf("%*c");       //清除缓冲区中的非法字符
printf("输入有误!请重新输入:");
}
scanf("%*[^\n]");   //清除缓冲区中的非法换行符
scanf("%*c");       //清除缓冲区中的非法字符


push(num);


printf("是否继续?输入y继续,否则停止。\n");
scanf("%c",&choice);
}while(choice == 'Y' || choice == 'y');


printf("栈中有效数据数%d个\n",size());


//出栈
while(!empty()){
printf("%d  ",pop());
}
printf("\n");


deinit();   //清理栈


return 0;
}


运行结果如下:


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值