2016-11-08 97 views
0

我試圖建立一個程序(Java),它會從用戶輸入字符串輸入到堆棧中,然後使用push和pop來反轉堆棧。當用戶輸入「end-line」時,程序將停止推入堆棧並以相反的順序打印用戶輸入的字符串?我需要幫助來編寫一個程序,該程序需要用戶輸入並使用堆棧反轉。

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 static void main(String [] args) 
{ 
    stackReversal s = new stackReversal(); 
    s.push("Hello"); 
    s.push("world"); 
    s.push("!"); 
    System.out.println("Strings:" + s); 
} 
} 
+0

我還沒有添加掃描儀在這個代碼中。 –

+0

你的問題是什麼? –

回答

1

請找到下面的代碼。我所做的只是重寫toString方法來打印節點項目。

現在我輸入1,2,3它將打印字符串:3 - > 2 - > 1作爲輸出..希望這有助於

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; 
} 

/* 
* (non-Javadoc) 
* 
* @see java.lang.Object#toString() 
* 
* This method prints the nodes in reerse order 
*/ 
@Override 
public String toString() { 

    StringBuilder nodes = new StringBuilder(); 

    Node node = first; 

    while (node != null) { 
     nodes.append(node.item).append(" -> "); 
     node = node.next; 
    } 

    if(isEmpty()) { 
     return ""; 
    } else { 
     return nodes.toString().substring(0, nodes.toString().length() - 4);  
    } 
} 

public static void main(String[] args) { 
    stackReversal s = new stackReversal(); 
    s.push("1"); 
    s.push("2"); 
    s.push("3"); 
    System.out.println("Strings:" + s); 
} 

}