棧的實現也有兩種方式:數組方式、和鏈表方式,我們前面知道表也是兩種方式,但是由於表經常要在表的中間刪除或插入數據,所以用數組實現不是一種很好的選擇,我們通常採用結點實現。但是在棧中,這種情況發生了變化,棧是一種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];
}