Stack comprehend。

#pragma once

template <class T>
class SLNode
{
public:
	T data;
	SLNode* next;
	SLNode() {};
	~SLNode() {};
};

template <class T>
class AStack
{
public:
	SLNode<T>* index;
	AStack()
	{
		index = new SLNode<T>();
		index->data = 0;
		index->next = nullptr;
	}
	void push(T data)
	{
		auto sl = new SLNode<T>();
		sl->data = data;
		sl->next = index;
		index = sl;
	}
	T pop()
	{
		if (index->next != nullptr && index->data != 0)
		{
			T dt = index->data;
			index = index->next;
			return dt;
		}
		else
		{
			return (T)nullptr;
		}
	}
};


// test   code
//AStack<int>* as = new AStack<int>();
//as->push(1);
//as->push(2);
//as->push(3);
//cout << as->pop();
//cout << as->pop();
//cout << as->pop();
//cout << as->pop();
//cout << as->pop();
//cout << as->pop();
//cout << as->pop();
//cout << as->pop();
// problem    if stack is null , return default value of T. 

发表评论

电子邮件地址不会被公开。 必填项已用*标注