栈的实现也有两种方式:数组方式、和链表方式,我们前面知道表也是两种方式,但是由于表经常要在表的中间删除或插入数据,所以用数组实现不是一种很好的选择,我们通常采用结点实现。但是在栈中,这种情况发生了变化,栈是一种LIFO性质的线性表,它不允许在中间插入数据。而且事先知道数据数量的应用场景也经常出现(如果不知道,那就用链表),所以我们下面将讲解栈的链表和数组实现。
栈的链表实现
一、创建栈
这和创建一个单链表是一样的,其实这里所谓的栈就是一个链表只能在表头插入与删除操作,这里我实现的是一个带表头的空栈。如下是创建完成后的结果。
Stack *Create_Stack(void)
{
Stack *head;
head = (Stack *)malloc(sizeof(Stack));
if(head == NULL)
exit(1);
head->data = 0;
head->next = NULL;
return head;
}
二、判断是否为空栈
int Is_Empty(Stack *stack)
{
return stack->next == NULL;
}
三、Push
下面是执行过程
void Push(Stack *stack, int data)
{
Stack *pioneer;
pioneer = (Stack *)malloc(sizeof(Stack));
if(pioneer == NULL)
exit(1);
else{
pioneer->data = data;
pioneer->next = stack->next;
stack->next = pioneer;
}
}
四、Pop
void Pop(Stack *stack)
{
Stack *pioneer;
if(Is_Empty(stack))
printf("Empty stack!!!");
else {
pioneer = stack->next;
stack->next = stack->next->next;
free(pioneer);
}
}
五、Top
int Top(Stack *stack)
{
if(!stack->next == NULL)
return stack->next->data;
else{
printf("Empty stack!!!\n");
return;
}
}
栈的数组实现
一、创建栈
头文件里的内容
#ifndef STACK_ARRAY_H_INCLUDED
#define STACK_ARRAY_H_INCLUDED
typedef struct stack{
int capacity;//栈的大小
int top_of_stack;//栈顶的浮标用来定位
int *array;//数组
}Stack;
#define MIN_STACK_SIZE 5
Stack *Create_Stack(int Max_element);
void Make_Stack_Empty(Stack *S);
int Is_Empty(Stack *S);
void Push(Stack *S, int data);
int Is_Full(Stack *S);
void Pop(Stack *S);
int Top(Stack *S);
#endif // STACK_ARRAY_H_INCLUDED
源文件中的内容
Stack *Create_Stack(int Max_element)
{
Stack *s;
if(Max_element < MIN_STACK_SIZE){
printf("Stack size is too small.");
exit(1);
}
s = (Stack *)malloc(sizeof(Stack));
if(s == NULL){
printf("Out of space !!");
exit(1);
}
s->array = (int *)malloc(sizeof(int) * Max_element);
if(s->array == NULL){
printf("Out of space !!");
exit(1);
}
s->capacity = Max_element;
Make_Stack_Empty(s);
}
二、使栈为空
void Make_Stack_Empty(Stack *S)
{
S->top_of_stack = -1;
}
三、判断栈是否为空
int Is_Empty(Stack *S)
{
return S->top_of_stack == -1;
}
四、判断栈是否满
int Is_Full(Stack *S)
{
return S->top_of_stack == (S->capacity - 1);
}
五、Push
void Push(Stack *S, int data)
{
if(Is_Full(S))
printf("Full stack !!");
else
S->array[++S->top_of_stack] = data;
}
六、Pop
void Pop(Stack *S)
{
if(Is_Empty(S))
printf("Empty stack !!");
else
S->top_of_stack--;
}
七、Top
int Top(Stack *S)
{
if(Is_Empty(S))
printf("Empty stack !!!");
else
return S->array[S->top_of_stack];
}