堆栈特点:后进先出(Last-In First-Out,LIFO)
基本操作:进栈(push)和出栈(pop)
其他操作:空堆栈不能执行pop操作,因此需要判断堆栈是否为空。堆栈如果存在最大长度限制,那么需要判断堆栈是否已满。
基本操作:进栈(push)和出栈(pop)
其他操作:空堆栈不能执行pop操作,因此需要判断堆栈是否为空。堆栈如果存在最大长度限制,那么需要判断堆栈是否已满。
一、数组实现堆栈
#include<stdio.h>
#include<stdlib.h>
using namespace std;
#define STACK_TYPE int
#define STACK_SIZE 100
void push(STACK_TYPE value);
STACK_TYPE pop(void);
STACK_TYPE top(void);
int is_Empty(void);
int is_full(void);
static STACK_TYPE stack[STACK_SIZE];
static int top_element = -1;
void push(STACK_TYPE value)
{
assert(!is_full());
top_element += 1;
stack[top_element] = value;
}
STACK_TYPE pop(void)
{
STACK_TYPE temp;
assert(!is_Empty());
temp = stack[top_element];
top_element -= 1;
return temp;
}
STACK_TYPE top(void)
{
assert(!is_Empty());
return stack[top_element];
}
int is_Empty()
{
return top_element == -1;
}
int is_full()
{
return top_element == STACK_SIZE - 1;
}
二、动态数组实现堆栈
#include<stdio.h>
using namespace std;
#define STACK_TYPE int
static STACK_TYPE *stack;
static size_t stack_size;
static int top_element = -1;
void create_stack(size_t size);
void destory_stack(void);
void push(STACK_TYPE value);
STACK_TYPE pop(void);
STACK_TYPE top(void);
int is_Empty();
int is_Full();
void create_stack(size_t size)
{
assert(stack_size==0);
stack_size = size;
stack = (STACK_TYPE*)malloc(stack_size * sizeof(STACK_TYPE));
assert(stack!=NULL);
}
void destory_stack()
{
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;
}
STACK_TYPE pop()
{
STACK_TYPE temp;
assert(!is_Empty());
temp = stack[top_element];
top_element -= 1;
return temp;
}
STACK_TYPE top()
{
assert(!is_Empty());
return stack[top_element];
}
int is_Empty()
{
assert(stack_size>0);
return top_element == - 1;
}
int is_Full()
{
assert(stack_size>0);
return top_element == stack_size-1;
}
三、链式堆栈
#include<stdio.h>
using namespace std;
#define FALSE 0
#define STACK_TYPE int
typedef struct STACK_NODE {
STACK_TYPE value;
struct STACK_NODE *next;
}StackNode;
static StackNode *stack;
void destory_stack();
void push(STACK_TYPE value);
void pop();
STACK_TYPE top();
int is_Empty();
int is_Full();
void destory_stack()
{
while (!is_Empty())
pop();
}
void push(STACK_TYPE value)
{
StackNode *new_node;
new_node = (StackNode*)malloc(sizeof(StackNode));
assert(new_node != NULL);
new_node->value = value;
new_node->next = stack;
stack = new_node;
}
void pop()
{
StackNode *first_node;
assert(!is_Empty);
first_node = stack;
stack = first_node->next;
free(first_node);
}
STACK_TYPE top()
{
assert(!is_Empty());
return stack->value;
}
int is_Empty()
{
return stack == NULL;
}
int is_Full()
{
return FALSE; //链式堆栈不会满
}