Algs4-1.3.48双向队列与栈
1.3.48双向队列与栈。用一个双向队列实现两个栈,保证每个栈操作只需要常数次的双向队列操作(请见练习1.3.33)。
答:
public class StackDouble<Item>
{
private Deque<Item> q=new Deque<Item>();
///////////Stack of Left
private int NLeft=0;
public boolean isEmptyLeft()
{return NLeft==0;}
public int sizeLeft()
{return NLeft;}
public void pushLeft(Item item)
{
q.pushLeft(item);
NLeft++;
}
public Item popLeft()
{
if (NLeft==0) return null;
Item item=q.popLeft();
NLeft--;
return item;
}
///////////Stack of Right
private int NRight=0;
public boolean isEmptyRight()
{return NRight==0;}
public int sizeRight()
{return NRight;}
public void pushRight(Item item)
{
q.pushRight(item);
NRight++;
}
public Item popRight()
{
if(NRight==0) return null;
Item item=q.popRight();
NRight--;
return item;
}
public static void main(String[] args)
{
StackDouble<String> s=new StackDouble<String>();
s.pushLeft("1");
s.pushLeft("2");
s.pushLeft("3");
//
s.pushRight("4");
s.pushRight("5");
s.pushRight("6");
StdOut.println("Stack of Left size is:"+s.sizeLeft());
StdOut.println("Stack of Right size is:"+s.sizeRight());
//
StdOut.println("Stack of Left element is:");
for(int i=0;i<7;i++)
StdOut.print(s.popLeft()+" ");
//
StdOut.println();
StdOut.println("Stack of Right element is:");
for(int i=0;i<7;i++)
StdOut.print(s.popRight()+ " ");
}
}
答:
public class StackDouble<Item>
{
private Deque<Item> q=new Deque<Item>();
///////////Stack of Left
private int NLeft=0;
public boolean isEmptyLeft()
{return NLeft==0;}
public int sizeLeft()
{return NLeft;}
public void pushLeft(Item item)
{
q.pushLeft(item);
NLeft++;
}
public Item popLeft()
{
if (NLeft==0) return null;
Item item=q.popLeft();
NLeft--;
return item;
}
///////////Stack of Right
private int NRight=0;
public boolean isEmptyRight()
{return NRight==0;}
public int sizeRight()
{return NRight;}
public void pushRight(Item item)
{
q.pushRight(item);
NRight++;
}
public Item popRight()
{
if(NRight==0) return null;
Item item=q.popRight();
NRight--;
return item;
}
public static void main(String[] args)
{
StackDouble<String> s=new StackDouble<String>();
s.pushLeft("1");
s.pushLeft("2");
s.pushLeft("3");
//
s.pushRight("4");
s.pushRight("5");
s.pushRight("6");
StdOut.println("Stack of Left size is:"+s.sizeLeft());
StdOut.println("Stack of Right size is:"+s.sizeRight());
//
StdOut.println("Stack of Left element is:");
for(int i=0;i<7;i++)
StdOut.print(s.popLeft()+" ");
//
StdOut.println();
StdOut.println("Stack of Right element is:");
for(int i=0;i<7;i++)
StdOut.print(s.popRight()+ " ");
}
}