Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package edu.brcc.maxfieldj.ch21Lab;
- import java.io.PrintStream;
- import java.util.EmptyStackException;
- import java.util.Scanner;
- public class GenericLinkedStack<E>
- {
- private class Node
- {
- E value;
- GenericLinkedStack<E>.Node next;
- Node(GenericLinkedStack<E>.Node val)
- {
- this.value = val;
- this.next = n;
- }
- }
- private GenericLinkedStack<E>.Node top = null;
- public boolean empty()
- {
- return this.top == null;
- }
- public void push(E s)
- {
- this.top = new Node(s, this.top);
- }
- public E pop()
- {
- if (empty()) {
- throw new EmptyStackException();
- }
- E retValue = this.top.value;
- this.top = this.top.next;
- return retValue;
- }
- public E peek()
- {
- if (empty()) {
- throw new EmptyStackException();
- }
- return this.top.value;
- }
- public String toString()
- {
- StringBuilder sBuilder = new StringBuilder();
- GenericLinkedStack<E>.Node p = this.top;
- sBuilder.append("[");
- while (p != null)
- {
- sBuilder.append(p.value);
- p = p.next;
- if (p != null) {
- sBuilder.append(" ");
- }
- }
- sBuilder.append("]");
- return sBuilder.toString();
- }
- public static void main(String[] args)
- {
- GenericLinkedStack<String> st = new GenericLinkedStack();
- System.out.println("Pushing: Amy Bob Chuck");
- System.out.println("Contents of Stack:");
- st.push("Amy");
- st.push("Bob");
- st.push("Chuck");
- System.out.println(st);
- String name = (String)st.pop();
- System.out.println("Popped: " + name);
- System.out.println("Contents of Stack:");
- System.out.println(st);
- GenericLinkedStack<Double> nums = new GenericLinkedStack();
- Scanner keyboard = new Scanner(System.in);
- System.out.println("RPN calculator");
- System.out.print(">");
- for (;;)
- {
- String input = keyboard.nextLine();
- double num2;
- double num1;
- try
- {
- double num = Double.parseDouble(input);
- nums.push(Double.valueOf(num));
- System.out.print(nums.peek() + ">");
- }
- catch (Exception e)
- {
- num2 = ((Double)nums.pop()).doubleValue();
- num1 = ((Double)nums.pop()).doubleValue();
- switch (input.charAt(0))
- {
- case '+':
- nums.push(Double.valueOf(num1 + num2));
- System.out.print(nums.peek() + ">");
- }
- }
- continue;
- nums.push(Double.valueOf(num1 - num2));
- System.out.print(nums.peek() + ">");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement