Algs4-1.4.28一个队列实现的栈
1.4.28一个队列实现的栈。使用一个队列实现一个栈,使得每个栈操作所需的队列操作数量为线性级别。提示:要删除一个元素,将队列中的所有元素一一出列,除了最后一个元素,应该将它删除并返回(这种方法的确非常低效)。
答:
![图片](http://r.photo.store.qq.com/psb?/f33bb27a-608a-4097-811a-86bbde18cf7a/f*FPVYFvLzKM8*LXsAVHXqowBO0a9BUdDj7zNa8vvcY!/o/dPgAAAAAAAAA&ek=1&kp=1&pt=0&bo=wAHXAMAB1wADACU!&tl=1&su=086810465&tm=1540515600&sce=0-12-12&rf=2-9)
public class E1d4d28<Item>
{
Queue<Item> q=new Queue<Item>();
public boolean isEmpty()
{
return q.isEmpty();
}
public int size()
{
return q.size();
}
public void push(Item item)
{
q.enqueue(item);
}
public Item pop()
{
int N=q.size();
while(N>1)
{
q.enqueue(q.dequeue());
N--;
}
Item item=q.dequeue();
return item;
}
public static void main(String[] args)
{
E1d4d28<String> s=new E1d4d28<String>();
while(!StdIn.isEmpty())
{
String item=StdIn.readString();
s.push(item);
}
StdOut.printf("Stack is Empty:%s\n",s.isEmpty());
StdOut.printf("Stack size is:%s\n",s.size());
StdOut.printf("Stack top element is:%s\n",s.pop());
StdOut.printf("Stack top element is:%s",s.pop());
}
}
答:
public class E1d4d28<Item>
{
Queue<Item> q=new Queue<Item>();
public boolean isEmpty()
{
return q.isEmpty();
}
public int size()
{
return q.size();
}
public void push(Item item)
{
q.enqueue(item);
}
public Item pop()
{
int N=q.size();
while(N>1)
{
q.enqueue(q.dequeue());
N--;
}
Item item=q.dequeue();
return item;
}
public static void main(String[] args)
{
E1d4d28<String> s=new E1d4d28<String>();
while(!StdIn.isEmpty())
{
String item=StdIn.readString();
s.push(item);
}
StdOut.printf("Stack is Empty:%s\n",s.isEmpty());
StdOut.printf("Stack size is:%s\n",s.size());
StdOut.printf("Stack top element is:%s\n",s.pop());
StdOut.printf("Stack top element is:%s",s.pop());
}
}