数据结构与算法_链式栈
程序员文章站
2022-06-05 15:05:07
...
LinkStack.h
#pragma once
#include <iostream>
using namespace std;
template<class T> class LinkStack; //前置声明
template<class T>
class ListNode
{
friend class LinkStack<T>;
private:
T data;
ListNode<T>* next;
//私有构造函数
ListNode(const T& theData, ListNode* n=0):data(theData), next(n)
{}
} ;
template<class T>
class LinkStack
{
public:
LinkStack():top(0){}
~LinkStack(){ MakeEmpty();}
bool IsEmpty() const;
T& Top() const;
void Push(const T& e);
void Pop();
void MakeEmpty();
private:
ListNode<T> *top;
} ;
template<class T>
void LinkStack<T>::MakeEmpty()
{
while(!IsEmpty())
{
Pop();
}
}
template<class T>
bool LinkStack<T>::IsEmpty() const
{
return (top == 0);
}
template<class T>
void LinkStack<T>::Push(const T& e)
{
//新创建一个节点赋值给top,在构造时让指针指向原来的top
top = new ListNode<T>(e, top);
}
template<class T>
T& LinkStack<T>::Top() const
{
if(this->IsEmpty())
throw "Stack is empty!";
else
return top->data;
}
template<class T>
void LinkStack<T>::Pop()
{
if(this->IsEmpty())
throw "Stack is empty, Cannot delete!";
ListNode<T> *DeleteNode = top;
top = top->next;
delete DeleteNode;
}
main.h
#include <iostream>
#include "LinkStack.h"
using namespace std;
int main()
{
LinkStack<int> List;
List.Push(10);
cout << List.Top() << endl;
List.Push(20);
cout << List.Top() << endl;
List.Push(30);
List.Pop();
cout << List.Top() << endl;
List.MakeEmpty();
cout << List.Top() << endl;
cout << "hello " << endl;
return 0;
}
上一篇: 芦蒿、藜蒿和茼蒿它们是同一种植物吗?芦蒿有哪些功效呢?
下一篇: 产妇黑米粥的功效有哪些