加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
MyStack.cc 1.39 KB
一键复制 编辑 原始数据 按行查看 历史
Ivan_Chien 提交于 2020-10-15 13:26 . auto-commit.sh: 10/15/20 13:26:31
#include <iostream>
#include <cstddef>
class Stack
{
struct Node
{
int data;
Node* prev;
Node* next;
Node() = default;
Node(int data_ = {}, Node* prev_ = nullptr, Node* next_ = nullptr)
: data(data_), prev(prev_), next(next_) { }
};
public:
Stack() {
this->len = 0u;
this->top_ = nullptr;
}
~Stack() {
this->clear();
}
void push(int item) {
if (top_ == nullptr) {
top_ = new Node(item);
} else {
top_->next = new Node(item, top_);
top_ = top_->next;
}
++len;
}
bool pop() {
if (size() == 0) {
return false;
} else {
auto new_top_ = top_->prev;
delete top_;
top_ = new_top_;
--len;
return true;
}
}
void clear() {
while (len != 0)
this->pop();
}
::size_t size() const {
return this->len;
}
bool empty() const {
return size() == 0;
}
int top() const {
return this->top_->data;
}
private:
::size_t len;
Node* top_;
};
int main()
{
::Stack stack;
std::cout << "pushing order: ";
for (int i = 0; i < 10; ++i) {
std::cout << i << ' ';
stack.push(i);
}
std::endl(std::cout);
std::cout << "popping order: ";
while (!stack.empty()) {
std::cout << stack.top() << ' ';
stack.pop();
}
std::endl(std::cout);
std::cout << "Is the stack now empty? " << std::boolalpha
<< stack.empty() << std::endl;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化