Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1.  
  2. public class LinkedStack<T> implements StackInterface<T> {
  3.  
  4. private Node<T> topNode;
  5.  
  6. public LinkedStack()
  7. {
  8. topNode = null;
  9. }
  10.  
  11.  
  12. @Override
  13. public boolean isEmpty() {
  14. // TODO Auto-generated method stub
  15. return topNode == null;
  16. }
  17.  
  18. @Override
  19. public T pop() {
  20.  
  21. T retVal = null;
  22. if(topNode != null)
  23. {
  24. retVal = topNode.data;
  25. topNode = topNode.next;
  26. }
  27. return retVal;
  28. }
  29.  
  30. @Override
  31. public void push(T entry) {
  32. Node<T> fresh = new Node<T>(entry, topNode);
  33.  
  34. topNode = fresh;
  35. }
  36.  
  37. /* Initializing the Node class */
  38. private class Node<T>
  39. {
  40. private T data;
  41. private Node<T> next;
  42.  
  43. public Node(T data)
  44. {
  45. this.data = data;
  46. this.next = null;
  47. }
  48.  
  49. public Node(T data, Node<T> next)
  50. {
  51. this.data = data;
  52. this.next = next;
  53. }
  54. }
  55.  
  56. public static void main(String[] args)
  57. {
  58. char [] a = "5 9 8 + 4 6 * * 7 + *".toCharArray();
  59. //char [] a = "4 5 +";
  60.  
  61. int N = a.length;
  62.  
  63. LinkedStack<Integer> s = new LinkedStack<Integer>();
  64. for(int i=0; i< N; i++)
  65. {
  66. if(a[i] == '+')
  67. s.push(s.pop() + s.pop());
  68. if(a[i] == '-')
  69. s.push(s.pop() - s.pop() );
  70. if(a[i] == '*')
  71. s.push(s.pop() * s.pop());
  72.  
  73. if(a[i] >= '0' && a[i] <= '9')
  74. s.push(0);
  75. while( (a[i] >= '0') && (a[i] <= '9') )
  76. s.push(10*s.pop() + (a[i++]-'0'));
  77. }
  78. System.out.println(s.pop()+ " ");
  79.  
  80.  
  81. }
  82.  
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement