Tony Kelly Tony Kelly - 1 year ago 88
Java Question

Create a linked-list of characters on a stack?

I have an assignment that I'm struggling with.

Write code based on referenced-based stack to implement the balance check of a user input string with ‘{’, ‘}’, ‘(’, ‘)’, and ‘[’, and ‘]’. For instance, if user inputs “(abc[d]e{f})”, your code should say that the expression is balanced.

I have the functions push / pop already written:

public void push(Object newItem) {
top = new Node(newItem, top);
} // end push

public Object pop(){
if (!isEmpty()) {
Node temp = top;
top = top.getNext();
return temp.getItem();
} else {
System.out.print("StackError on " +
"pop: stack empty");
return null;
} // end if
} // end pop

However, what I am struggling with is understanding how to create a new node for each character. Could somebody please help me?

Answer Source

Since your assignment instructions ask you to "Write code based on referenced-based stack", it seems your question is more about how to convert each of user's input string into a node. In that case, you can convert them first to a list of chars simply like this:

public class Main {
    public static void main(String[] args){
        String str = new String("[(a)bcde]");

And then use ASCII table to tell whether it's a special character. eg: in above code:

(int) str.toCharArray()[0]  // will show ASCII code of '[', 91

Some useful implementations about Reference-based Stack

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download