代码拉取完成,页面将自动刷新
#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;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。