Quick actions

cmd+k|ctrl+k

Navigation

Languages

顺序栈基本操作

Snippet info

Language

Cpp

Visibility

public

Author

qwas

Created

2024-05-20T07:17:47.375262Z

Updated

2024-05-20T07:19:32.589076Z

#include <stdio.h>
#define MaxSize 50 // 定义栈中元素的最大个数
# define ElemType int

int main()
{
  printf("Hello Stack");
  return 0;
    
}


typedef struct
{
  ElemType data[MaxSize]; // 存放栈中元素
  int top;                // 栈顶指针
} SqStack;

/**
 * 初始化时
 * top == -1 top 指向栈顶元素
 * top == 0 top 指向栈顶元素的下一个位置
 * */

// 初始化
void InitStack(SqStack &S)
{
  S.top = -1;
}

// 判栈空
bool StackEmpty(SqStack S)
{
  if (S.top == -1)
    return true;
  else
    return false;
}

// 进栈
bool Push(SqStack &S, ElemType x)
{
  if (S.top == MaxSize - 1)
    return false;
  S.data[++S.top] = x;
  return true;
}

// 出栈
bool Pop(SqStack &S, ElemType &x)
{
  if (S.top == -1) // 栈空
    return false;
  x = S.data[S.top]; // x 为出栈的元素
  return true;
}

// 读取栈顶元素
/**
 * 仅读取栈顶元素,不出栈
 */
bool GetTop(SqStack S, ElemType &x)
{
  if (S.top == -1)
    return false;
  x = S.data[S.top];
  return true;
}
INFO