// 链栈.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "LinkStack.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
LinkStack<int> stack;
int i;
cout << "请输入入栈元素: ";
cin >> i;
while(i != -1)
{
stack.Push(i);
cin >> i;
}
cout << "出栈: " <<stack.Pop()<< endl;
cout << "判栈空: "<< stack.Empty() << endl;
cout << "取栈顶元素: " <<stack.GetTop()<< endl;
return 0;
}
template<class T>
struct Node
{
T data;
Node<T> *next;
};
template<class T>
class LinkStack
{
public:
LinkStack();
T Pop(); //出栈
void Push(T x); //入栈
bool Empty(); //判栈空
T GetTop(); //取栈顶元素
private:
Node<T> *top;
};
template<class T>
// LinkStack.h
//
LinkStack<T>::LinkStack()
{
top = NULL;
}
template<class T>
void LinkStack<T>::Push(T x)
{
Node<T> *p = new Node<T>;
p->data=x;
p->next=top;
top=p;
}
template<class T>
T LinkStack<T>::Pop()
{
if(!top)throw "下溢";
T x=top->data;
Node<T> *p=top->next;
delete top;
top=p;
return x;
}
template<class T>
bool LinkStack<T>::Empty()
{
return top ? false:true;
}
template<class T>
T LinkStack<T>::GetTop()
{
if(!top) throw "下溢";
return top->data;
}
链栈
最新推荐文章于 2022-08-17 11:17:33 发布