2
我试图制作一个程序,以先入先出的顺序打印用户输入。我目前已经制作了一个打印堆栈LIFO的程序(后进先出)。然而,我将如何去实现一个队列,以FIFO(先进先出)顺序显示堆栈的输出。我想实现一个队列,将反转堆栈和打印堆栈FIFO?
我以下代码:
import java.util.*;
public class stackReversal {
private class Node {
private String item;
private Node next;
}
private Node first = null;
public boolean isEmpty() {
return (first == null);
}
public void push(String s) {
Node node = new Node();
node.item = s;
node.next = first;
first = node;
}
public String pop() {
if (first == null)
throw new RuntimeException("Stack Empty!");
String result = first.item;
first = first.next;
return result;
}
public String popString() {
String result = "";
Node current = first;
while (current != null) {
result += current.item;
current = current.next;
}
return result;
}
public String toString() {
StringBuilder nodes = new StringBuilder();
Node node = first;
while (node != null) {
nodes.append(node.item).append("\n");
node = node.next;
}
if(isEmpty()) {
return "";
} else {
return nodes.toString().substring(0, nodes.toString().length());
}
}
class Queue{
Node first, last;
public void enqueue(Node n){
if(first == null){
first = n;
last = first;
}else{
last.next = n;
last = n;
}
}
public Node dequeue(){
if(first == null){
return null;
}else{
Node temp = new Node(first);
first = first.next;
return temp;
}
}
}
public static void main(String[] args)
{
stackReversal s = new stackReversal();
Scanner input = new Scanner(System.in);
System.out.print("Enter strings:");
String in = "";
while (!in.equals("end-of-input"))
{
in = input.nextLine();
if (in.equals("end-of-input"))
break;
else
s.push(in);
}
System.out.println("Strings:"+"\n" + s);
}
}
请注意,您的代码无法编译,你确实使用类'Node' –
为什么扭转不存在的构造函数,而不是将商品加入队列结构,而不是堆栈。或者,您可以实现一个Deque(双端队列)https://en.wikipedia.org/wiki/Double-ended_queue并获取堆栈和队列行为。另请参阅界面'Deque' https://docs.oracle.com/javase/7/docs/api/java/util/Deque.html –