代码拉取完成,页面将自动刷新
#pragma once
#include <iostream>
#include "stack.h"
using namespace std;
namespace linked_stack
{
template <class TData>
struct LinkedNode
{
TData data;
LinkedNode<TData>* next;
explicit LinkedNode(LinkedNode<TData>* next = NULL)
: next(next) {}
explicit LinkedNode(const TData& data, LinkedNode<TData>* next = NULL)
: data(data), next(next) {}
};
}
//// 链式栈模板类
//template <typename TData> class LinkedStack;
//// 重载<<
//template <typename TData> ostream& operator<<(ostream& os, const LinkedStack<TData>& stack);
template <class TData>
class LinkedStack :public Stack<TData>
{
// 重载<<
friend ostream& operator<< <>(ostream& os, const LinkedStack<TData>& stack);
private:
// 栈顶指针(头节点)
linked_stack::LinkedNode<TData>* top_;
public:
LinkedStack() :top_(NULL) {}
~LinkedStack();
virtual bool push(const TData& data) override;
virtual bool pop(TData& data) override;
bool pop();
virtual bool top(TData& data) const override;
virtual bool isEmpty() const override;
virtual int length() const override;
void clear();
};
template<typename TData>
inline ostream& operator<<(ostream& os, const LinkedStack<TData>& stack)
{
os << "栈中元素个数:" << stack.length() << endl;
linked_stack::LinkedNode<TData>* cur = stack.top_;
while (cur)
{
os << cur->data << endl;
cur = cur->next;
}
return os;
}
template<class TData>
inline LinkedStack<TData>::~LinkedStack()
{
this->clear();
}
// 就是单链表的头插法
template<class TData>
inline bool LinkedStack<TData>::push(const TData& data)
{
linked_stack::LinkedNode<TData>* node = new linked_stack::LinkedNode<TData>(data);
if (!node)
throw bad_alloc();
node->next = this->top_;
this->top_ = node;
return true;
}
template<class TData>
inline bool LinkedStack<TData>::pop(TData& data)
{
if (this->isEmpty())
return false;
linked_stack::LinkedNode<TData>* temp = this->top_;
this->top_ = this->top_->next;
data = temp->data;
delete temp;
temp = NULL;
return true;
}
template<class TData>
inline bool LinkedStack<TData>::pop()
{
if (this->isEmpty())
return false;
linked_stack::LinkedNode<TData>* temp = this->top_;
this->top_ = this->top_->next;
delete temp;
temp = NULL;
return true;
}
template<class TData>
inline bool LinkedStack<TData>::top(TData& data) const
{
if (this->isEmpty())
return false;
data = this->top_->data;
return true;
}
template<class TData>
inline bool LinkedStack<TData>::isEmpty() const
{
return this->top_ == NULL;
}
template<class TData>
inline int LinkedStack<TData>::length() const
{
int length = 0;
linked_stack::LinkedNode<TData>* cur = this->top_;
while (cur)
{
length++;
cur = cur->next;
}
return length;
}
template<class TData>
inline void LinkedStack<TData>::clear()
{
while (!this->top_)
{
linked_stack::LinkedNode<TData>* target = this->top_;
this->top_ = this->top_->next;
delete target;
// 防止出现悬空指针
target = NULL;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。