栈的实现-顺序栈和链栈

本文主要给出我对栈的实现,包括顺序栈和链栈两种实现方式。

常量声明

common.h

#ifndef common_H
#define common_H

/* 函数结果状态码 */
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
//#define OVERFLOW -2
//#define UNDERFLOW -3

/* 类型定义 */
typedef int Status;     // Status是函数的类型,其值是函数结果状态码
typedef int ElemType;   // ElemType是数据类型

#endif

顺序栈声明

SeqStack.h

#ifndef SeqStack_h
#define SeqStack_h
#define STACKSIZE 1024
#include 
#include "common.h"

// 顺序栈存储结构声明
struct SeqStack{
    ElemType data[STACKSIZE];
    int top; // 初始化为0,指向栈顶下一个元素

    SeqStack(){ std::memset(this, 0, sizeof(SeqStack)); }
};

// 顺序栈基本操作
Status push( SeqStack& stk, ElemType x );
Status pop( SeqStack& stk );
ElemType top( SeqStack& stk );
bool empty( SeqStack& stk );

#endif

顺序栈实现(SeqStack.cpp)

  • 入栈
    思路:注意判断栈溢出的情形
Status push( SeqStack& stk, ElemType x ){
    if( STACKSIZE == stk.top ){
        std::cerr << "Stack Overflow";
        return OVERFLOW;
    }

    stk.data[stk.top++] = x;

    return OK;
}
  • 出栈
    思路:注意栈空的情形
Status pop( SeqStack& stk ){
    if( !stk.top ){
        std::cerr << "Stack Underflow";
        return UNDERFLOW;
    }
    stk.top--;
    return OK;
}
  • 获取栈顶
    思路:注意栈空的情形
ElemType top( SeqStack& stk ){
    if( empty(stk) ){
        std::cerr << "Stack is empty!";
        return ERROR;
    }
    return stk.data[stk.top-1];
}
  • 判断栈是否为空
    思路:栈空条件,栈满条件的判断
bool empty( SeqStack& stk ){
    return !stk.top;
}

链栈声明

LinkedStack.h

#ifndef LinkedStack_h
#define LinkedStack_h
#include "common.h"
#include 

/* 链栈节点声明 */
struct ListNode
{
    ElemType data;
    ListNode* next;

    ListNode() : data(0), next(NULL) {}
    ListNode( ElemType x ) : data(x), next(NULL) {}
};

typedef ListNode* LinkedStack; // LinkedStack是指向ListNode类型的指针

// 链栈基本操作
Status push( LinkedStack& top, ElemType x );
Status pop( LinkedStack& top );
ElemType top( LinkedStack& top );
bool empty( LinkedStack& top );

#endif

注意一定,链栈在实现的时候,本质是靠一个头指针,也就是top指针。该指针相当于头指针的作用,出栈入栈都是围绕该指针进行。

链栈实现(LinkedStack.cpp)

  • 入栈
Status push( LinkedStack& top, ElemType x ){
    LinkedStack cur = new ListNode(x);
    if(!cur){
        std::cerr << "Not enough space!";
        return ERROR;
    }

    if(!top) top = cur;
    else{
        cur->next = top;
        top = cur; // top一直指向头指针的位置
    }

    return OK;
}
  • 出栈
    思路:注意栈空的情形
Status pop( LinkedStack& top ){
    if(!top){
        std::cerr << "Stack Underflow";
        return UNDERFLOW;
    }
    LinkedStack nex = top->next;
    delete top;
    top = nex;

    return OK;
}
  • 获得栈顶
    思路:注意栈空的情形
ElemType top( LinkedStack& top ){
    if(!top){
        std::cerr << "Stack Underflow";
        return UNDERFLOW;
    }
    return top->data;
}
  • 判断栈是否为空
bool empty( LinkedStack& top ){
    return !top;
}

你可能感兴趣的:(数据结构实现)