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;
}
相關文章
相關標籤/搜索