Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class LinkedStack<T> implements StackInterface<T> {
- private Node<T> topNode;
- public LinkedStack()
- {
- topNode = null;
- }
- @Override
- public boolean isEmpty() {
- // TODO Auto-generated method stub
- return topNode == null;
- }
- @Override
- public T pop() {
- T retVal = null;
- if(topNode != null)
- {
- retVal = topNode.data;
- topNode = topNode.next;
- }
- return retVal;
- }
- @Override
- public void push(T entry) {
- Node<T> fresh = new Node<T>(entry, topNode);
- topNode = fresh;
- }
- /* Initializing the Node class */
- private class Node<T>
- {
- private T data;
- private Node<T> next;
- public Node(T data)
- {
- this.data = data;
- this.next = null;
- }
- public Node(T data, Node<T> next)
- {
- this.data = data;
- this.next = next;
- }
- }
- public static void main(String[] args)
- {
- char [] a = "5 9 8 + 4 6 * * 7 + *".toCharArray();
- //char [] a = "4 5 +";
- int N = a.length;
- LinkedStack<Integer> s = new LinkedStack<Integer>();
- for(int i=0; i< N; i++)
- {
- if(a[i] == '+')
- s.push(s.pop() + s.pop());
- if(a[i] == '-')
- s.push(s.pop() - s.pop() );
- if(a[i] == '*')
- s.push(s.pop() * s.pop());
- if(a[i] >= '0' && a[i] <= '9')
- s.push(0);
- while( (a[i] >= '0') && (a[i] <= '9') )
- s.push(10*s.pop() + (a[i++]-'0'));
- }
- System.out.println(s.pop()+ " ");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement