设顺序栈S中有2n个元素,从栈顶到栈底的元素依次为a2n,a2n-1,…,a1,要求通过一个循环队列重新排列栈中元素,使得从栈顶到栈底的元素依次为a2n,a2n-2,…,a2,a2n-1,a2n-3,…,a1,设计算法实现,空闲和时间复杂度均为O(n)。
#include <iostream>
using namespace std;
const int Size=100;
template<typename T>
class Node
{
public:
T data;
Node* next;
};
template<typename T>
class SeqStack
{
public:
SeqStack(T a[],int l)
{
top=-1;
if(l>Size||l<0) throw "error";
for(int i=0;i<l;i++)
{
data[++top]=a[i];
}
}
T pop()
{
if(top==-1)throw "error";
return data[top--];
}
void push(T x)
{
if(top==Size) throw"error";
data[++top]=x;
}
void Output()
{
if(top==-1)throw "error";
for(int i=top;i>=0;i--)
{
cout<<data[i]<<" ";
}
cout<<endl;
}
private:
T data[Size];
int top;
};
template<typename T>
class CirLinkQueue
{
public:
CirLinkQueue(){length=0;}
void Enqueue(T x)
{
Node<T>* p=new Node<T>;
p->data=x;
if(length==0)
{
front=new Node<T>;
rear=front=p;
rear->next=front;
front->next=rear;
}
else
{
rear->next=p;
rear=p;
p->next=front;
length++;
}
}
T DeQueue()
{
Node<T>* p=front;
int x=p->data;
rear->next=front->next;
front=front->next;
delete p;
length--;
return x;
}
private:
Node<T>* front,* rear;
int length;
};
int main()
{
int x[8]= {1,2,3,4,5,6,7,8};
SeqStack<int> S(x,8);
S.Output();
CirLinkQueue<int> b;
for(int i=0;i<8;i++)
{
b.Enqueue(S.pop());
}
for(int i=0;i<8;i++)
{
if(i%2==0)
{
b.Enqueue(b.DeQueue());
}
else
S.push(b.DeQueue());
}
for(int i=0;i<4;i++)
{
b.Enqueue(S.pop());
}
for(int i=0;i<4;i++)
{
S.push(b.DeQueue());
}
for(int i=0;i<4;i++)
{
b.Enqueue(S.pop());
}
for(int i=0;i<8;i++)
{
S.push(b.DeQueue());
}
S.Output();
}