C语言 stack 简单实现.

// main.h
#ifndef MAIN_H
#define MAIN_H

#define TRUE 1
#define FALSE 0

//节点
struct stack_cell{
	void *data;
	struct stack_cell* next;
};


struct stack{
	struct stack_cell* top;
};

//
struct stack* stack_new();
int stack_puch(struct stack* stack,void* data);
void  stack_free(struct stack* stack);
void  stack_pop(struct stack* stack);
void *stack_top(struct stack* stack);
int stack_empty(struct stack* stack);
#endif


// main.c
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "main.h"

struct stack* stack_new()
{
	struct stack* new_stack = (struct stack*)malloc(sizeof(struct stack));
	if(NULL == new_stack)
	{
		return NULL;
	}

	new_stack->top = NULL;
	return new_stack;
}

int stack_push(struct stack* new_stack,int * data)
{
	struct stack_cell* new_cell = (struct stack_cell *)malloc(sizeof(struct stack_cell));

	if(NULL  == new_cell)
	{
		return 0;
	}

	// data;
	new_cell->data = data;
	//找到自己要挂在在哪个点上
	new_cell->next = new_stack->top;
	//更新栈的最顶端的信息.
	new_stack->top= new_cell;
	return 0;
}

// 只做内存的释放工作,不做数据的输出,
void   stack_pop(struct stack* new_stack)
{
	struct stack_cell* stack_cell_new =  new_stack->top;
	new_stack->top = stack_cell_new->next;
	free(stack_cell_new);
}

// 数据的输出,
void *  stack_top(struct stack* stack)
{
	return stack->top->data;
}

int stack_empty(struct stack* stack)
{
	return stack->top == NULL;
}




void  stack_free(struct stack* new_stack)
{
	struct stack_cell *p;

	if(!new_stack)
	{
		return ;
	}
	

	p= new_stack->top;
	while(p)
	{
		struct stack_cell *next = p->next;
		free(p);
		p=next;
	}

	free(new_stack);

}



int main()
{
	int a=0,b=1,c=2,d=3;
	int   *e,*f,*g;
	struct stack* new_stack = stack_new();
	
	if(NULL == new_stack)
	{
		return FALSE;
	}


	stack_push(new_stack,&a);
	stack_push(new_stack,&b);
	stack_push(new_stack,&c);
	stack_push(new_stack,&d);


	// top
	e = (int *)stack_top(new_stack);
	printf("%d\r\n",*e);
	// pop
	stack_pop(new_stack);

	f= (int*)stack_top(new_stack);
	printf("%d\r\n",*f);
	stack_pop(new_stack);

	g=(int*)stack_top(new_stack);
	printf("%d\r\n",*g);
	stack_pop(new_stack);



	stack_free(new_stack);
	return 0;
}

 

转载于:https://my.oschina.net/u/1579560/blog/862659

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值