栈实现(链式结构)

链式结构

#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;

栈操作

  1. 初始化 :

时间复杂度: 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;
}
  1. 清空 :

时间复杂度: O(1)

void clearStack(StackPtr stack_ptr) {
  stack_ptr->top = NULL;
}
  1. 销毁 :

时间复杂度: 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;
}
  1. 入栈 :

时间复杂度: 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;
}
  1. 出栈 :

时间复杂度: 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;
}
  1. 取栈顶元素 :

时间复杂度: 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;
}
  1. 判断栈空 :

时间复杂度: O(1)

bool isEmpty(StackPtr stack_ptr){
  if(stack_ptr && stack_ptr->top != NULL) return false;
  return true;
}
  1. 获取栈大小 :

时间复杂度: 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;
}

猜你喜欢

转载自blog.csdn.net/kelly_fumiao/article/details/85262174