栈的实现
- 栈
- 示例代码
- 开发环境
- 运行结果
栈
栈本着先进后出的原则,来存取数据。作为数据结构中的一种,这里不多介绍相关栈。仅以此文记录C++中栈的实现,可帮助提升编程能力与对栈的理解。
示例代码
直接上代码。
SeqStack.h
#pragma once#define MAX_SIZE 1024
#define TRUE 1
#define FALSE 0
typedef struct SEQSTACK {void *data[MAX_SIZE];int size;
}SeqStack;class MySeqStack
{
public:MySeqStack();~MySeqStack();void init();void pushStack(void *data);void * getTopStack();void popStack();int isEmpty();int getSizeStack();void clearStack();
private:SeqStack *m_stack;
};
SeqStack.cpp
#include "SeqStack.h"
#include <iostream>using namespace std;MySeqStack::MySeqStack()
{
}MySeqStack::~MySeqStack()
{if (m_stack != nullptr) {delete m_stack;m_stack = nullptr;}
}void MySeqStack::init()
{m_stack = new SeqStack;if (m_stack == nullptr) {cout << "分配内存为空" << endl;}else {m_stack->size = 0;for (int i = 0; i < m_stack->size; ++i) {m_stack->data[i] = nullptr;}}
}void MySeqStack::pushStack(void * data)
{if (m_stack->size == MAX_SIZE){return;}if (m_stack == nullptr){return;}if (data == nullptr) {return;}m_stack->data[m_stack->size] = data;m_stack->size++;
}void * MySeqStack::getTopStack()
{if (m_stack == nullptr){return nullptr;}if (m_stack->size == 0){return nullptr;}return m_stack->data[m_stack->size-1];
}void MySeqStack::popStack()
{if (m_stack == nullptr){return ;}if (m_stack->size == 0){return ;}m_stack->data[m_stack->size - 1] = nullptr;m_stack->size--;
}int MySeqStack::isEmpty()
{if (m_stack == nullptr){return -1;}if (m_stack->size == 0) {return TRUE;}return FALSE;
}int MySeqStack::getSizeStack()
{return m_stack->size;
}void MySeqStack::clearStack()
{if (m_stack == nullptr){return ;}for (int i = 0; i < m_stack->size; ++i){m_stack->data[i] = nullptr;}m_stack->size = 0;
}
main.cpp
#include <iostream>
#include "SeqStack.h"using namespace std;typedef struct PERSON {char name[64];int age;int score;
}Person;void test()
{MySeqStack *stack = new MySeqStack;stack->init();Person p1 = { "hudf",3,56 };Person p2 = { "akso",4,67 };Person p3 = {"及家属的",6,88};Person p4 = { "口袋",7,98 };Person p5 = { "husdh",8,34 };stack->pushStack(&p1);stack->pushStack(&p2);stack->pushStack(&p3);stack->pushStack(&p4);stack->pushStack(&p5);while (stack->getSizeStack() > 0){Person *data = (Person*)stack->getTopStack();cout << "name = " << data->name << " age= " << data->age << " score=" << data->score << endl;stack->popStack();}delete stack;stack = nullptr;
}
int main()
{test();return 0;
}// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
开发环境
vs2017控制台输出程序。