堆栈
堆栈最鲜明的特点就是先进后出,堆栈接口的三个基本操作:
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;
}