⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mystack.h

📁 组播密钥的批次更新算法
💻 H
字号:
// MyStack.h: interface for the CMyStack class.
//
//////////////////////////////////////////////////////////////////////

#pragma once

#include <iostream>
using namespace std;

template <typename T>
class CMyStack  
{
public:
	friend ostream& operator << <T> (ostream& out,CMyStack<T> &stack);
	
	CMyStack();
	virtual ~CMyStack();
	T top();
	T pop();
	void push(const T &key);
	CMyStack<T>& operator =(const CMyStack<T> &stack);
	void clear();
	
protected:
	template <typename NodeType>
	class CNode
	{
	public:
		CNode()
		{
			next=0;
		}
		NodeType key;
		CNode<NodeType>* next;
	};
	CNode<T>* m_head;
public:
	class iterator
	{
	public:
		iterator(CMyStack<T> &stack):now(stack.m_head){}
		~iterator(){}
		bool hasNext()
		{
			return (now!=0);
		}
		
		T GetCurrentItem()
		{
			try
			{
				return (now->key);
			}
			catch(...)
			{
			}
		}

		void next()
		{
			now=now->next;
		}
	private:
		CNode<T>* now;
	};
};

template <typename T>
CMyStack<T>::CMyStack():m_head(0)
{
}

template <typename T>
CMyStack<T>::~CMyStack()
{
	this->clear();
}

template<typename T>
void CMyStack<T>::push(const T &key)
{
	try
	{
		CNode<T>* temp=new CNode<T>;
		temp->key=key;
		temp->next=this->m_head;
		this->m_head=temp;
	}
	catch (std::bad_alloc &exception)
	{
		cerr<<"allocate memory failed."<<endl;
	}
}

template <typename T>
T CMyStack<T>::pop()
{
	T result=this->top();
	CNode<T>* temp=this->m_head;
	this->m_head=temp->next;
	delete temp;
	return result;
}

template <typename T>
T CMyStack<T>::top()
{
	if (m_head!=0)
		return m_head->key;
	else
		throw exception("the stack is empty!");
}

template <typename T>
CMyStack<T>& CMyStack<T>::operator =(const CMyStack<T> &stack)
{
	if(this != &stack)
	{
		clear();
		
		if(stack.m_head!=0)
		{
			this->m_head=new CNode<T>;
			this->m_head->key=stack.m_head->key;
		}
		CNode<T>* dest=this->m_head;
		CNode<T>* source=stack.m_head->next;
		while(source!=0)
		{
			dest->next=new CNode<T>;
			dest->next->key=source->key;
			dest=dest->next;
			source=source->next;
		}
	}
	return *this;
}

template <typename T>
void CMyStack<T>::clear()
{
	CNode<T>* temp=m_head;
	while(temp!=0)
	{
		m_head=temp->next;
		delete temp;
		temp=m_head;
	}
}

template <typename T>
ostream& operator << (ostream& out,CMyStack<T>& stack)
{
	CMyStack<T>::CNode<T>* temp=stack.m_head;
	while(temp!=0)
	{
		out<<(temp->key);
		if (temp->next!=0)
			out<<" , ";
		temp=temp->next;
	}
    return out;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -