C堆栈实现

堆栈

堆栈最鲜明的特点就是先进后出,堆栈接口的三个基本操作:
pop 把顶部元素从堆栈移除
push 把一个新值压入到堆栈的顶部
top 返回顶部元素的值
堆栈实现:
stack.h

#define STACK_TYPE int 

void push(STACK_TYPE value);

void pop(void);

STACK_TYPE top(void);

int is_empty(void);

int is_full(void);

void  create_stack(size_t size);

void destroy_stack(void);


stack.c 用静态数组实现

#include <assert.h>
#include "stack.h"


#define STACK_SIZE   100

static STACK_TYPE   stack[STACK_SIZE];
static int          top_element = -1;



void push(STACK_TYPE value)
{
	assert( !is_empty() );

	top_element += 1;
	stack[top_element] = value;
}

void pop(void)
{
	assert(!is_empty());
	top_element -= 1;
}

STACK_TYPE top(void)
{
	assert( !is_empty() );
	return stack[top_element];
}

int is_empty(void)
{
	return top_element == -1;
}

int is_full(void)
{
	return top_element == STACK_SIZE - 1;
}

void  create_stack(size_t size)
{

}

void destroy_stack(void)
{
	
}

stack.c 用动态数组实现

#include <assert.h>
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

static STACK_TYPE* stack;
static size_t      stack_size;
static int         top_element = -1;

void create_stack(size_t size)
{
	assert( stack_size == 0);
	stack_size = size;
	stack = malloc( stack_size * sizeof( STACK_TYPE ) );
	assert( stack != NULL);
}

void destroy_stack(void)
{
	assert( stack_size > 0);
	stack_size = 0;
	free( stack );
	stack = NULL;
}

void push(STACK_TYPE value)
{
	assert( !is_full() );
	top_element += 1;
	stack[top_element] = value;

}

void pop(void)
{
	assert(!is_empty());
	top_element -= 1;
}

STACK_TYPE top(void)
{
	assert( !is_empty() );
	return stack[ top_element ];
}

int is_empty(void)
{
	assert( stack_size > 0);
	return top_element == -1;
}
int is_full(void)
{
	assert( stack_size > 0);
	return top_element == stack_size - 1;

}

stack.c 用链表实现

#include <assert.h>
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

#define FALSE 0

typedef  struct  STACK_NODE {
	STACK_TYPE   value;
	struct STACK_NODE* next;
} StackNode;

static StackNode* stack;


void create_stack(size_t size)
{
}

void destroy_stack(void)
{
	while (!is_empty())
	{
		pop();
	}
}

void push(STACK_TYPE value)
{
	StackNode* new_node;

	new_node = malloc(sizeof(StackNode));
	assert( new_node != NULL);
	new_node->next = stack;
	new_node->value = value;
	stack = new_node;

}

void pop(void)
{
	StackNode* first_node;
	assert(!is_empty());
	first_node = stack;
	stack = first_node->next;
	free(first_node);
}

STACK_TYPE top(void)
{
	assert(!is_empty());
	return stack->value;
}

int is_empty(void)
{
	return stack == NULL;
}
int is_full(void)
{
	return FALSE;

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值