1.4.30一个栈和一个steque实现的双向队列。使用一个栈和steque实现一个双向队列(请见练习1.3.32),使得双向队列的每个操作所需的栈和steque操作均摊后为一个常数。
答:
public class E1d4d30<Item>
{
Stack<Item> s=new Stack<Item>();
Steque<Item> ste=new Steque<Item>();
public boolean isEmpty()
{
return s.isEmpty() && ste.isEmpty();
}
public int size()
{
return s.size()+ste.size();
}
public void pushLeft(Item item)
{
ste.push(item);
}
public Item popLeft()
{
if(s.isEmpty())
while(!ste.isEmpty())
s.push(ste.pop());
//
Item item=s.pop();
return item;
}
public void pushRight(Item item)
{
ste.push(item);
}
public Item popRight()
{
if(ste.isEmpty())
while(!s.isEmpty())
ste.push(s.pop());
return ste.pop();
}
public static void main(String[] args)
{
E1d4d30<String> d=new E1d4d30<String>();
StdOut.printf("Deque is empty:%s\n",d.isEmpty());
d.pushLeft("1");
StdOut.printf("Deque size is:%d\n",d.size());
d.pushRight("2");
StdOut.printf("Deque size is:%d\n",d.size());
StdOut.printf("popLeft is:%s\n",d.popLeft());
StdOut.printf("popLeft is:%s\n",d.popLeft());
//
d.pushLeft("1");
d.pushRight("2");
d.pushRight("3");
StdOut.printf("popLeft is %s\n",d.popLeft());
StdOut.printf("popRight is %s\n",d.popRight());
}
}
答:
![图片](https://i-blog.csdnimg.cn/blog_migrate/f570ddf8f2d62fde1da462eb95a8996f.png)
public class E1d4d30<Item>
{
Stack<Item> s=new Stack<Item>();
Steque<Item> ste=new Steque<Item>();
public boolean isEmpty()
{
return s.isEmpty() && ste.isEmpty();
}
public int size()
{
return s.size()+ste.size();
}
public void pushLeft(Item item)
{
ste.push(item);
}
public Item popLeft()
{
if(s.isEmpty())
while(!ste.isEmpty())
s.push(ste.pop());
//
Item item=s.pop();
return item;
}
public void pushRight(Item item)
{
ste.push(item);
}
public Item popRight()
{
if(ste.isEmpty())
while(!s.isEmpty())
ste.push(s.pop());
return ste.pop();
}
public static void main(String[] args)
{
E1d4d30<String> d=new E1d4d30<String>();
StdOut.printf("Deque is empty:%s\n",d.isEmpty());
d.pushLeft("1");
StdOut.printf("Deque size is:%d\n",d.size());
d.pushRight("2");
StdOut.printf("Deque size is:%d\n",d.size());
StdOut.printf("popLeft is:%s\n",d.popLeft());
StdOut.printf("popLeft is:%s\n",d.popLeft());
//
d.pushLeft("1");
d.pushRight("2");
d.pushRight("3");
StdOut.printf("popLeft is %s\n",d.popLeft());
StdOut.printf("popRight is %s\n",d.popRight());
}
}