C++语言题目3

//采用面向对象的方法实现一个stack类,操作包括进栈,出栈,取栈顶元素,显示整个栈;
//(只要内存够用,可以无限次进栈)
#include"iostream"
using namespace std;

class Node{
private:
  int x;
  Node* next;
public:
  Node(int data)
  {
    x = data;
  }
  void setNext(Node* p)
  {
    next = p;
  }
  Node* getNext()
  {
    return next;
  }
  int setData(int number)
  {
    x = number;
  }
  int getData()
  {
    return x;
  }
  ~Node(){}
};

class Stack
{
private:
  Node *nodelast;
public:
  Stack()
  {
    nodelast = new Node(0);
    nodelast->setNext(NULL);
  }
  void pushData(int x)
  {
    Node *p = new Node(x);
    p->setNext(nodelast->getNext());
    nodelast->setNext(p);
    nodelast->setData(nodelast->getData()+1);
  }
  int popData()
  {
    int value;
    int error = 0;
    Node *p = nodelast->getNext();
    Node *q = p;
    if((p != NULL))
      {
	value = q->getData();
	p = p->getNext();
	nodelast->setNext(p);
	nodelast->setData(nodelast->getData()-1);
	delete q;
	return value;
      }
    else
      {
	throw error;
      }
  }
  int getTopData()
  {
    int value;
    int error = 0;
    Node *p = nodelast->getNext();
    if((p != NULL))
      {
	value = p->getData();
	return value;
      }
    else
      {
	throw error;
      }
  }
  void showStack()
  {
    int i;
    Node *p = nodelast;
    cout<<"Top ";
    for(i=0; i< nodelast->getData(); i++)
      {
	p = p->getNext();
	cout<< p->getData()<<" ";
      }
    cout<<"End"<<endl;
  }
};
int main()
{
  int value;
  Stack s;
  try
    {
      cout<<"出栈:"<<endl;
      s.popData();
    }
  catch(int)
    {
      cout<<"栈为空!"<<endl;
    }
  cout<<"入栈1,3,2:"<<endl;
  s.pushData(1);
  s.pushData(3);
  s.pushData(2);
  s.showStack();
  try
    {
      value = s.popData();
      cout<<"出栈:"<<value<<endl;
      s.showStack();
      value = s.getTopData();
      cout<<"当前栈顶元素:"<<value<<endl;
      s.showStack();
    }
  catch(int)
    {
      cout<<"栈为空!"<<endl;
    }
  cout<<"入栈3,4,5:"<<endl;
  s.pushData(3);
  s.pushData(4);
  s.pushData(5);
  s.showStack();
  return 1;
}