利用栈实现队列的操作

来源:互联网 发布:php curl 下载pdf文件 编辑:程序博客网 时间:2024/06/05 04:00
#include<iostream>
#include<stdexcept>
using namespace std;
class Stack
{
public:
// 初始化为一个空堆栈
Stack() :m_top(NULL){}
~Stack()
{
for (Node* next; m_top; m_top = next)
{
next = m_top->m_next;
delete m_top;
}
}  
void push(int data)
{
/*Node* node = new Node;
node->m_data = data;
node->m_next = m_top;
m_top = node;*/
m_top = new Node(data, m_top);
}
int pop(void)
{
if (empty())
throw UnderFlow();
int data = m_top->m_data;
Node* next = m_top->m_next;
delete m_top;
m_top = next;
return data;
}
bool empty() const
{
return !m_top;
}
private: //下溢异常
class UnderFlow :public exception
{
const char* what(void) const throw()
{
return "堆栈下溢";
}
};
//结点
class Node
{
public:
Node(int data = 0, Node* next = NULL) :m_data(data),
m_next(next){}


int m_data;//数据
Node* m_next;//后指针
};


Node* m_top; //栈顶指针
};


//基于堆栈的队列


class Queue
{
public:
//成员变量支持无参构造
//压入成员函数
void push(int data)
{
m_i.push(data);
}
//弹出
int pop(void)
{
if (m_o.empty())
{
if (m_i.empty())
throw underflow_error("队列下溢");
while (!m_i.empty())
m_o.push(m_i.pop());
}
return m_o.pop();
}
//判空
bool empty(void) const
{
return m_i.empty() && m_o.empty();
}
private:
Stack m_i;//输入栈
Stack m_o;//输出栈


};
int main()
{
try{
Queue queue;
for (int i = 0; i < 10; ++i)
queue.push(i);
cout << queue.pop() << endl;//0
cout << queue.pop() << endl;//1
cout << queue.pop() << endl;//2
cout << queue.pop() << endl;//3
queue.push(10);
queue.push(11);
while (!queue.empty())
cout << queue.pop() << endl;
}
catch (exception& ex)
{
cout << ex.what() << endl;
return -1;
}
}
0 0
原创粉丝点击