栈结构体:
数组或者指针,用于存放栈数据,指针的话需要分配空间
栈顶位置,用于记录当前栈顶在哪
栈的大小
typedef struct
{
ElemType *elem;
int top;
int size;
}STACK_SQ;
//初始化栈,给栈分配空间,初始值,成功返回true,出错返回false
bool InitStack(STACK_SQ &sq, int size);
//入栈,需要判断是否已达栈顶,如果达到栈顶,退出。成功返回true,出错返回false
bool PushStack(STACK_SQ &sq, ElemType e);
//出栈,需要判断是否为空栈,是则退出,出栈成功返回出栈元素,出错返回-1
int PopStack(STACK_SQ &sq, ElemType &e);
//判断栈是否为空,如果为空,返回true,出错返回false;
bool IsEmptyStack(STACK_SQ sq);
//获取栈顶数据,需要判断是否是空栈,获取成功返回true,失败返回false
bool GetTopStack(STACK_SQ sq, ElemType &e);
//获取栈的元素个数,空的话返回0,返回元素个数
int GetNumStack(STACK_SQ sq);
//清空栈
void ClearStack(STACK_SQ &sq);
//销毁栈
void DestroyStack(STACK_SQ &sq);
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
using std::cout;
using std::endl;
typedef int ElemType;
typedef struct
{
ElemType *elem;
int top;
int size;
}STACK_SQ;
//初始化栈
bool InitStack(STACK_SQ &sq, int size)
{
sq.elem = (ElemType *)malloc(size * sizeof(ElemType));
if(sq.elem == NULL) return false;
sq.top = 0;
sq.size = size;
return true;
}
//入栈
bool PushStack(STACK_SQ &sq, ElemType e)
{
if(sq.top >= sq.size )
{
cout<<"out of stack size"<<endl;
return false;
}
sq.elem[sq.top++] = e;
//sq.elem+(sq.top++) = e;
return true;
}
//出栈
int PopStack(STACK_SQ &sq, ElemType &e)
{
if(sq.top == 0)
{
cout<<"stack is empty!"<<endl;
return -1;
}
e = sq.elem[sq.top - 1];
sq.top--;
return e;
}
//判断栈是否为空
bool IsEmptyStack(STACK_SQ sq)
{
if(0 == sq.top)
return true;
return false;
}
//获取栈顶元素
bool GetTopStack(STACK_SQ sq, ElemType &e)
{
if(0 == sq.top)
{
cout<<"stack is empty!"<<endl;
return false;
}
e = sq.elem[sq.top - 1];
return true;
}
//获取栈的元素个数
int GetNumStack(STACK_SQ sq)
{
int size = sq.top;
return size;
}
//清空栈
void ClearStack(STACK_SQ &sq)
{
sq.top = 0;
//sq.size = 0;
}
//销毁栈
void DestoryStack(STACK_SQ &sq)
{
sq.top = 0;
sq.size = 0;
free(sq.elem);
sq.elem = NULL;
}
const int SIZE = 10;
int main()
{
cout<<"init stack"<<endl;
STACK_SQ sq;
if(!InitStack(sq, SIZE))
{
cout<<"init stack fail!"<<endl;
return -1;
}
cout<<"init stack success!"<<endl;
int a[SIZE] = {2,2,3,3,4,4,5,5,6,7};
for(int i = 0; i < SIZE; i++)
{
if(!PushStack(sq, a[i]))
{
cout<<a[i]<<":push stack faile!"<<endl;
break;
}
cout<<"push stack:"<<a[i]<<endl;
}
cout<<"push stack success!"<<endl;
cout<<"num stack:"<<GetNumStack(sq)<<endl;
ElemType e;
for(int i = 0; i < SIZE; i++)
{
if(PopStack(sq, e) != -1)
{
cout<<"pop stack:"<<e<<endl;
}
}
cout<<"clear stack"<<endl;
ClearStack(sq);
cout<<sq.size<<endl;
cout<<"destory stack"<<endl;
DestoryStack(sq);
cout<<sq.size<<endl;
}
参考:
https://github.com/huihut/interview/edit/master/DataStructure/SqStack.cpp#L1