1.4.29两个栈实现的steque。用两个栈实现一个steque(请见练习1.3.32),使得每个steque操作所需的栈操作均摊后为一个常数。
答:
public class E1d4d29<Item>
{
Stack<Item> s1=new Stack<Item>();
Stack<Item> s2=new Stack<Item>();
public boolean isEmpty()
{
return s1.isEmpty() && s2.isEmpty();
}
public int size()
{
return s1.size()+s2.size();
}
public void push(Item item)
{
s1.push(item);
}
public Item pop()
{
if(s1.isEmpty())
while(!s2.isEmpty())
s1.push(s2.pop());
//
Item item=s1.pop();
return item;
}
public void enqueue(Item item)
{
s1.push(item);
}
public static void main(String[] args)
{
E1d4d29<String> s=new E1d4d29<String>();
while(!StdIn.isEmpty())
{
String item=StdIn.readString();
s.push(item);
}
s.enqueue("a");
StdOut.printf("Stack is Empty:%s ",s.isEmpty());
StdOut.printf("Stack size is:%s ",s.size());
while(!s.isEmpty())
{
StdOut.println(s.pop());
}
}
}
答:
public class E1d4d29<Item>
{
Stack<Item> s1=new Stack<Item>();
Stack<Item> s2=new Stack<Item>();
public boolean isEmpty()
{
return s1.isEmpty() && s2.isEmpty();
}
public int size()
{
return s1.size()+s2.size();
}
public void push(Item item)
{
s1.push(item);
}
public Item pop()
{
if(s1.isEmpty())
while(!s2.isEmpty())
s1.push(s2.pop());
//
Item item=s1.pop();
return item;
}
public void enqueue(Item item)
{
s1.push(item);
}
public static void main(String[] args)
{
E1d4d29<String> s=new E1d4d29<String>();
while(!StdIn.isEmpty())
{
String item=StdIn.readString();
s.push(item);
}
s.enqueue("a");
StdOut.printf("Stack is Empty:%s ",s.isEmpty());
StdOut.printf("Stack size is:%s ",s.size());
while(!s.isEmpty())
{
StdOut.println(s.pop());
}
}
}