一、栈是什么?
栈是一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端为栈顶,另一端为栈底。栈中元素遵循先进后出的原则
假设我们依次将1, 2, 3, 4压入栈中
二、具体实现
废话不多说,来,上代码!
1.stack.h
#include <iostream>
#include <sperror.h>
#include <cassert>
using namespace std;
typedef int Type;
struct Stack
{
Type* a;
int top;
int capacity;
};
void Init_stack(Stack* s);
void Push_back(Stack* s, Type x);
void Pop(Stack* s);
Type get_top(Stack* s);
int stack_size(Stack* s);
bool is__empty(Stack* s);
void stack_Destroy(Stack* s);
2.stack.cpp
代码如下(示例):
#include "Stack.h"
void Init_stack(Stack* s)
{
s->capacity = 5;
s->top = 0;
s->a = (Type*)malloc(sizeof(Type) * s->capacity);
}
void check(Stack* s)
{
if (s->capacity == s->top)
{
int newcapacity = s->capacity * 2;
Type* tmp = (Type*)realloc(s->a, sizeof(Type) * newcapacity);
if (tmp != NULL)
{
s->a = tmp;
s->capacity = newcapacity;
}
else
perror("realloc:");
}
}
void Push_back(Stack* s, Type x)
{
check(s);
s->a[s->top] = x;
s->top++;
}
bool is__empty(Stack* s)
{
if (s->top <= 0)
return true;
else
return false;
}
void Pop(Stack* s)
{
assert(!is__empty(s));
s->top--;
}
Type get_top(Stack* s)
{
assert(!is__empty(s));
return s->a[s->top-1];
}
int stack_size(Stack* s)
{
return s->top;
}
void stack_Destroy(Stack* s)
{
s->a = NULL;
s->capacity = 0;
s->top = 0;
s = NULL;
}
3.test.cpp
#include "Stack.h"
void menu()
{
cout << "---------------------------------------------" << endl;
cout << "----1.入栈-----------------2.出栈------------" << endl;
cout << "----3.获得栈顶-------------4.判空------------" << endl;
cout << "----5.获取栈内元素长度-----6.销毁栈----------" << endl;
cout << "---------------------------------------------" << endl;
}
enum function
{
Exit,
push_back,
pop,
get_topval,
isempty,
get_size,
destroy
};
void test()
{
Stack s;
Init_stack(&s);
int choice = 0;
do {
menu();
cin >> choice;
switch (choice)
{
case push_back:
int x;
cout << "输入要入栈的元素:";
cin >> x;
Push_back(&s, x);
break;
case pop:
Pop(&s);
break;
case get_topval:
cout << get_top(&s) << endl;
break;
case isempty:
if (is__empty(&s))
cout << "Yes" << endl;
else
cout << "No" << endl;
break;
case get_size:
cout << stack_size(&s) << endl;
break;
case destroy:
stack_Destroy(&s);
break;
case Exit:
cout << "退出!" << endl;
}
} while (choice);
}
int main()
{
test();
}
总结
栈是一种后进先出的数据结构,由于作者水平和经验不多,目前直到的具体应用场景为二叉树的遍历和图的深度优先遍历方面,随着以后学习的深入,我会进一步补充和修改这方面。