
C++: 根据题目要求,写出程序和输出结果,急,求高手帮忙
C++程序:
#include "iostream"
using namespace std;
#define MAX 100
typedef int ElemType;
//链表结点结构
typedef struct node {
ElemType data;
struct node *next;
}Node;
//顺序栈
class Stack
{
public:
ElemType base[MAX];
int top;
Stack()
{
top = 0;
}
//入栈
void Push(ElemType elem)
{
if(IsFull())
{
cout<<"栈空间已满,不能入栈"<<endl;
return;
}
base[top++] = elem;
}
//出栈
ElemType Pop()
{
if(IsEmpty())
{
cout<<"栈空间为已空,不能出栈"<<endl;
return NULL;
}
return base[--top];
}
//判断栈是否为空
bool IsEmpty()
{
if(top == 0)
{
return true;
}
return false;
}
//判断栈是否为满
bool IsFull()
{
if(top >= MAX)
{
return true;
}
return false;
}
};
//链队列
class Queue
{
public:
Node *front;
Node *rear;
Queue()
{
front = NULL;
rear = NULL;
}
//入队列
void EnQueue(ElemType data)
{
Node *p = new(Node);
p->data = data;
p->next = NULL;
if(rear == NULL)
{
rear = p;
front = p;
}
else
{
rear->next = p;
rear = p;
}
}
//出队列
ElemType DeQueue()
{
Node *p;
ElemType value;
if(front == NULL)
{
return NULL;
}
else if(front->next == NULL)
{
value = front->data;
delete front;
rear = NULL;
front = NULL;
return value;
}
else
{
p = front;
front = front->next;
value = p->data;
delete p;
return value;
}
}
bool IsEmpty()
{
if(front == NULL)
{
return true;
}
return false;
}
//输出全部队列元素
void list()
{
for(Node *p=front; p!=NULL; p=p->next)
{
cout<<p->data<<"\t";
}
}
};
int main()
{
Queue q = Queue();
Stack s = Stack();
q.EnQueue(1);
q.EnQueue(2);
q.EnQueue(3);
cout<<"队列逆置前:";
q.list();
cout<<endl;
while(! q.IsEmpty())
{
s.Push(q.DeQueue());
}
while(! s.IsEmpty())
{
q.EnQueue(s.Pop());
}
cout<<"队列逆置后:";
q.list();
return 0;
}
运行测试: