链式结构
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef int ElemType;
typedef enum {overflow, underflow, success, fatal} Status;
typedef struct node{
ElemType ele;
struct node * next;
}Node,*NodePtr;
typedef struct stack{
NodePtr top;
}Stack,*StackPtr;
栈操作
- 初始化 :
时间复杂度: O(1)
Status initStack(StackPtr *stack_ptr){
Status s = success;
(*stack_ptr) = (StackPtr) malloc(sizeof(Stack));
if(!(*stack_ptr)) {
s = fatal;
return s;
} else{
(*stack_ptr)->top = NULL;
}
return s;
}
- 清空 :
时间复杂度: O(1)
void clearStack(StackPtr stack_ptr) {
stack_ptr->top = NULL;
}
- 销毁 :
时间复杂度: O(1)
void destroyStack(StackPtr *stack_ptr) {
while(!isEmpty((*stack_ptr))){
NodePtr deleteNode = (*stack_ptr)->top;
(*stack_ptr)->top = deleteNode -> next;
free(deleteNode);
deleteNode = NULL;
}
free((*stack_ptr));
(*stack_ptr) = NULL;
}
- 入栈 :
时间复杂度: O(1)
Status stack_push(StackPtr stack_ptr, ElemType ele){
Status s = success;
NodePtr newNode = (NodePtr) malloc(sizeof(Node));
if(newNode) {
newNode -> ele = ele;
newNode -> next = stack_ptr->top;
stack_ptr -> top = newNode;
}else{
s = fatal;
}
return s;
}
- 出栈 :
时间复杂度: O(1)
Status stack_pop(StackPtr stack_ptr,ElemType *ele){
Status s = success;
if(isEmpty(stack_ptr)){
s = underflow;
}else{
(*ele) = stack_ptr->top->ele;
NodePtr deleteNode = stack_ptr -> top;
stack_ptr -> top = deleteNode -> next;
free(deleteNode);
deleteNode = NULL;
}
return s;
}
- 取栈顶元素 :
时间复杂度: O(1)
Status stack_top(StackPtr stack_ptr,ElemType *ele){
Status s = success;
if(isEmpty(stack_ptr)){
s = underflow;
}else{
(*ele) = stack_ptr->top->ele;
}
return s;
}
- 判断栈空 :
时间复杂度: O(1)
bool isEmpty(StackPtr stack_ptr){
if(stack_ptr && stack_ptr->top != NULL) return false;
return true;
}
- 获取栈大小 :
时间复杂度: O(1)
int getLength(StackPtr stack_ptr){
if(!isEmpty(stack_ptr)) {
NodePtr tmpPtr = stack_ptr->top;
int count = 0;
while(tmpPtr){
count ++;
tmpPtr = tmpPtr->next;
}
return count;
}
return 0;
}