码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 两个队列实现堆栈

时间:2014-09-01 10:29:32      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:os   io   sp   new   c   ad   c++   ios   as   

//构建队列


#include<iostream>
using namespace std;
struct queuenode
{
int data;
queuenode* next;
};
class queue
{
private:
queuenode* head;
public:
queue(){head=new queuenode;head->next=NULL;}
~queue();
void push(int data);
void removenode(int data);
int pop();
void print();
};
void queue:: push(int data)
{
queuenode*p=head;
queuenode*q=new queuenode;
q->data=data;
q->next=NULL;


while(p->next!=NULL)
p=p->next;
p->next=q;


}
int queue::pop()
{
queuenode*p=head->next;
if(p==NULL)
{
cout<<"the queue is empty"<<endl;
return NULL;
}
else
{
head->next=p->next;
cout<<"出队元素:"<<p->data<<endl;
return p->data;
delete p;
p=NULL;
}
}
void queue:: print()
{
queuenode*p=head;
while(p->next!=NULL)
{
cout<<p->next->data<<" ";
p=p->next;
}
cout<<endl;
}
queue::~queue()
{
queuenode*p;
while (head->next)
{
p = head;
head = head->next;
delete p;
}
delete head;
head=NULL;
p=NULL;
}
int main()
{
queue queue1;
queue queue2;
queue1.push (1);
queue1.push (2);
queue1.push (3);
queue1.push (4);
queue1.push (5);
queue1.print();
queue2.push(queue1.pop());
queue2.push(queue1.pop());
queue2.push(queue1.pop());
queue2.push(queue1.pop());
queue1.pop();
queue2.print();
return 0;
}

C++ 两个队列实现堆栈

标签:os   io   sp   new   c   ad   c++   ios   as   

原文地址:http://www.cnblogs.com/wordwarwordwar/p/3948649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!