一、栈的抽象数据类型
ADT 栈(stack)
Data
同线性表。元素具有相同地方类型,相邻的元素具有前驱和后继关系
Operation
InitStack(*S):初始化操作,建立一个空栈S
DestroyStack(*S):若栈存在,则销毁他
ClearStack(*S):将栈清空
StackEmpty(S):若栈为空,返回true。否则返回false
GetTop(S,*e);若栈存在且非空,用e返回S的栈顶元素
Push(*S,e):若栈S存在,插入新元素e到栈S中并成为栈顶元素
Pop(*S,*e):删除栈S存在中栈顶的元素,并用e返回其值
StackLength(S):返回栈S的元素个数
endADT
栈是限定仅在表尾进行插入和删除的操作
test.hpp
#ifndef TEST_H_
#define TEST_H_
#include"malloc.h"
#define MAXSIZE 100
typedef int SElemType;
typedef struct
{
SElemType data[MAXSIZE];
int top;
}SqStack;
//InitStack(*S):初始化操作,建立一个空栈S
SqStack * initStack();
//DestroyStack(*S):若栈存在,则销毁他
void destroyStack(SqStack * S);
//ClearStack(*S):将栈清空
void clearStack(SqStack * S);
//StackEmpty(S):若栈为空,返回true。否则返回false
bool stackEmpty(const SqStack * S);
//StackLength(S):返回栈S的元素个数
int stackLength(const SqStack S);
//GetTop(S,*e);若栈存在且非空,用e返回S的栈顶元素
void getTop(const SqStack S, SElemType * e);
//Push(*S,e):若栈S存在,插入新元素e到栈S中并成为栈顶元素
void push(SqStack * S, const SElemType e);
//Pop(*S,*e):删除栈S存在中栈顶的元素,并用e返回其值
void pop(SqStack * S);
#endif // !TEST_H_
#pragma once
test.cpp
#include"test.h"
//InitStack(*S):初始化操作,建立一个空栈S
SqStack * initStack() {
SqStack *S = (SqStack *)malloc(sizeof(SqStack));
S->top = 0;
return S;
}
//DestroyStack(*S):若栈存在,则销毁他
void destroyStack(SqStack * S) {
if (S->top > 0)
free(S);
}
//ClearStack(*S):将栈清空
void clearStack(SqStack * S) {
if (S->top > 0)
{
for (size_t i = S->top; i >= 0; i--)
{
S->data[i] = 0;
}
S->top = 0;
}
}
//StackEmpty(S):若栈为空,返回true。否则返回false
bool stackEmpty(const SqStack * S) {
if (S->top > 0)
return false;
else
return true;
}
//StackLength(S):返回栈S的元素个数
int stackLength(const SqStack S) {
return S.top;
}
//GetTop(S,*e);若栈存在且非空,用e返回S的栈顶元素
void getTop(const SqStack S, SElemType * e) {
if (S.top > 0)
*e = S.data[S.top];
}
//Push(*S,e):若栈S存在,插入新元素e到栈S中并成为栈顶元素
void push(SqStack * S, const SElemType e) {
if (S->top < MAXSIZE)
{
S->data[S->top] = e;
++S->top;
}
}
//Pop(*S,*e):删除栈S存在中栈顶的元素,并用e返回其值
void pop(SqStack * S) {
S->data[S->top] = 0;
--S->top;
}
main.cpp
#include<iostream>
#include"test.h"
void showStack(const SqStack S);
int main()
{
SqStack * S = initStack();
std::cout << stackEmpty(S) << std::endl;
push(S, 1);
push(S, 2);
push(S, 3);
push(S, 4);
push(S, 5);
push(S, 6);
push(S, 7);
push(S, 8);
push(S, 9);
push(S, 10);
std::cout << stackLength(*S) << std::endl;
showStack(*S);
pop(S);
std::cout << stackLength(*S) << std::endl;
showStack(*S);
return 0;
}
void showStack(const SqStack S) {
if (S.top < 0)
{
std::cerr << "空栈!" << std::endl;
return;
}
else
{
for (size_t i = 0; i < S.top; i++)
{
std::cout << S.data[i] << " ";
}
std::cout << std::endl;
}
}