C++编一个堆栈,会的进

来源:百度知道 编辑:UC知道 时间:2024/05/26 01:55:34
题目:请模拟建立整型堆栈IntStack,用于存取整型数据。假定现在有两个整型堆栈的实例IntStackA和IntStackB,请将B中的数据导入A,并输出显示数据导入前后的A和B的状态。 急,在线等

#include <iostream>

using namespace std;

class IntStack;

class StackNode
{
private:
friend class IntStack;
StackNode(int item, StackNode *n = NULL) : data(item), next(n) {}

int data;
StackNode *next;
};

class IntStack
{
public:
IntStack() : top(NULL) {}
IntStack(const IntStack &other);
~IntStack() { Clear(); }

void Push(const int item); // 入栈
bool Pop(int &item); // 出栈
bool Top(int &item) const; // 获取栈顶元素
void Output() const; // 打印内容
void Clear(); // 清空堆栈

bool IsEmpty() const
{ return (top == NULL); }

private:
StackNode *top;
};

IntStack::IntStack(const IntStack &other) : top(NULL)
{
StackNode *cursor = other.top;

while (cursor)
top = new StackNode(cursor->data, top);

}

void IntStack::Clear()
{