java - I need help to write a program that takes input from user and reverses using a stack? -
i’m trying build program (java) take string input user puts stack , reverses stack using push , pop. when user inputs “end-line” program stop pushing stack , print strings entered user in reverse order ?
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); } }
please find below code. did override tostring method print nodes item.
now inputting 1,2,3 print strings:3 -> 2 -> 1 output.. hope helps
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() * * method prints 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); }
}
Comments
Post a Comment