您的位置:首页 > 编程语言 > C语言/C++

C++ 使用单向链表实现Stack

2017-05-07 21:34 323 查看
使用单向链表实现栈结构是一种简单且容易理解的方式

1、首先要创建一个节点类或者是结构体,这个结构体包括了该节点的下一个节点和该节点的值

template
struct node
{
T value;  //储存的值
node* next;
node() :next(nullptr) {} //构造函数
node(T t) :value(t), next(nullptr) {}
};

2、声明Stack类
template<class T>
class MyStack
{
public:
//构造函数,包括一个起始的Node和元素个数
MyStack() { _length = 0;_headNode = new node<T>(); };
~MyStack();
bool clear();
bool isEmpty();
int  GetLength();
const T GetTop();

bool Push(const T elem);

bool Pop(T &oPopValue);
void printStack();

private:
int _length;
node<T> *_headNode;

};
3、实现类
template<class T>
MyStack<T>::~MyStack()
{
while (!isEmpty())
Pop();
if (_headNode)
delete _headNode;
}

template<class T>
bool MyStack<T>::clear()
{
while(_headNode->next)
{
T elemtop;
bool isuccess = Pop(elemtop);
if (!isucc)
{
return false;
}
}
return true;
}

template<class T>
bool MyStack<T>::isEmpty()
{
if (!_length)
{
return true;
}
else
return false;
}

template<class T>
int MyStack<T>::GetLength()
{
return _length;
}

template<class T>
const T MyStack<T>::GetTop()
{
if (_headNode->next != nullptr)
{
T pValue = _headNode->next->value;
return pValue;
}

}

template<class T>
bool MyStack<T>::Push(const T elem)
{
node<T>* pNode = new node<T>(elem);
//采用头插法,即pNode代替栈顶的,所以pNode的下一个应为head的下一个;
pNode->next = _headNode->next;
_headNode->next = pNode;
_length++;
return true;
}

template<class T>
bool MyStack<T>::Pop(T &oPopValue)
{
if (_headNode->next!=nullptr)
{
node<T>* TopNode = _headNode->next;
_headNode->next = TopNode->next();
oPopValue = TopNode->value;
_length--;
delete  TopNode;
return true;
}
else
return false
}

template<class T>
void MyStack<T>::printStack()
{
if (_headNode->next != nullptr)
{
node<T> *pNode = _headNode->next;
cout << pNode->value << endl;
while (pNode->next)
{
cout << pNode->next->value << endl;
pNode = pNode->next;
}

}
}
4、上述实现了stack的基本功能,其他功能可以继续拓展,然后测试
int main()
{
MyStack<int> *opStack = new MyStack<int>();
int a;
while (cin>>a)
{
opStack->Push(a);
}

opStack->printStack();
system("pause");
}


5、测试结果
输入:1 2 3 4 5
输出:5 4 3 2 1

参考文章 http://blog.csdn.net/u013445530/article/details/43381833 http://blog.csdn.net/yzl_rex/article/details/6692500 http://blog.csdn.net/qq_15718789/article/details/52743278
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: