栈的解析及C++实现(2)

template<class T>
T LinkStack<T>::pop()
{
 if(topPointer==NULL)
  throw "下溢";
 Node <T> *p;
 p=topPointer;
 T rtndata = topPointer->data;
 topPointer=topPointer->next;
 delete p;
 return rtndata;
}

template<class T>
T LinkStack<T>::top()
{
 if(topPointer==NULL)
  throw "Empty";
 return topPointer->data;
}

template<class T>
bool LinkStack<T>::empty()
{
 if(topPointer==NULL)
  return true;
 return false;
}

#endif

测试文件:LStackTest.cpp

#include<iostream>
#include "LinkStack.h"
using namespace std;

int main()
{
 string tmp;
 LinkStack<string> *astack = new LinkStack<string>;
 
 cout<<"main"<<endl;
 
  //将"cat"、"dog"、"pig"依次推入栈中
 astack->push("cat");
    astack->push("dog");
    astack->push("pig");
   
    // 将“栈顶元素”赋值给tmp,并删除“栈顶元素”
    tmp = astack->pop();
    cout<<"tmp="<<tmp<<endl;
   
    // 只将“栈顶”赋值给tmp,不删除该元素
    tmp = astack->top();
    cout<<"tmp="<<tmp<<endl;
   
    astack->push("duck");
   
    while(!astack->empty())
    {
     tmp = astack->pop();
     cout<<"tmp="<<tmp<<endl;
 }
 return 0;
}

STL中自带的“栈”

头文件:#include <stack>

测试文件:StackTest.cpp

#include<iostream>
#include<stack>
using namespace std;

int main()
{
 int tmp = 0;
 stack<int> *astack = new stack<int>;
 
 cout<<"main"<<endl;
 
 //将10, 20, 30 依次推入栈中
 astack->push(10);
    astack->push(20);
    astack->push(30);
   
    // 删除“栈顶元素”,pop操作不返回栈顶数据
    astack->pop();
    cout<<"tmp="<<tmp<<endl;
   
    // 只将“栈顶”赋值给tmp,不删除该元素
    tmp = astack->top();
    cout<<"tmp="<<tmp<<endl;
   
    astack->push(40);
   
    while(!astack->empty())
    {
     tmp = astack->top();
     cout<<"tmp="<<tmp<<endl;
     astack->pop();
 }
 return 0;
}

注意:STL中自带的stack的pop操作不返回栈顶元素,只进行删除动作

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/2a8470568896e75f48d9115f2d018a51.html