Question

In: Computer Science

Stack Class //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Queue Class public class Stack { private java.util.ArrayList pool = new java.util.ArrayList(); pu

Stack Class

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Queue Class

public class Stack {
private java.util.ArrayList pool = new java.util.ArrayList();
public Stack() {
}
  
public Stack(int n) {
pool.ensureCapacity(n);
}
  
public void clear() {
pool.clear();
}
  
public boolean isEmpty() {
return pool.isEmpty();
}
  
public Object topEl() {
if (isEmpty())
throw new java.util.EmptyStackException();
return pool.get(pool.size()-1);
}
  
public Object pop() {
if (isEmpty())
throw new java.util.EmptyStackException();
return pool.remove(pool.size()-1);
}
  
public void push(Object el) {
pool.add(el);
}
  
public String toString() {
return pool.toString();
}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

public class Queue {
private java.util.LinkedList list = new java.util.LinkedList();
  
public Queue() {
}
  
public void clear() {
list.clear();
}
  
public boolean isEmpty() {
return list.isEmpty();
}
  
public Object firstEl() {
return list.getFirst();
}
  
public Object dequeue() {
return list.removeFirst();
}
  
public void enqueue(Object el) {
list.add(el);
}
  
public String toString() {
return list.toString();
}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

MAIN

import java.util.*;

public class StacksTest {
   public static void main(String[] args) {
       Stack s = new Stack();
       s.push(new Integer(3));
       s.push(new Integer(5));
       s.push(new String("hi"));
       while(!s.isEmpty()) {
           System.out.print(s.pop() + " ");
       }
      
       s.clear(); //Empty the contents of the stack
      
       System.out.println("\nHere's how I reverse a string: ");
       Scanner k = new Scanner(System.in);
       System.out.print("Enter a string> ");
       String input = k.nextLine();
      
       for(int i = 0; i < input.length(); i++)
           s.push(input.charAt(i) + "");
          
       System.out.println("The reversed string is: ");
       while(!s.isEmpty()) {
           System.out.print(s.pop());
       }
      
       System.out.println();
      
   }
}

///////////////////////////////////////////////////////////////////Lab Exercises.//////////////////////////////////////////////////////////////////////

Lab Exercises.

2. Write a method (in the class StackTest) public static boolean isPalindrome(String input) that checks if a given string is a palindrome using a stack. Test your method using the following strings: civic, madam, apple.

2. Write a method public static Stack reverse(Stack s) that reverses the order of elements on stack s using a Queue. Test your method using some example stacks.

2. Write a method public static boolean isBalanced(String expression), that checks if a given mathematical expression is balanced or not. The algorithm for evaluating parentheses is as follows: (a) Remove all non-parentheses from a mathematical expression. (b) Given an opening parenthesis, i.e., a ‘[‘, a ‘(‘ or a ‘{‘, push it onto the stack. (c) Given a closing parenthesis, pop an opening parenthesis from the stack: (i) if the closing parenthesis and the opening parenthesis match, it is a successful match (ii) if the parentheses do not match, the expression is not balanced (iii) if the stack is empty, the expression is not balanced (d) if, at the end of the program, the stack is empty, then the expression is balanced.

For example: [3 + (2 – 4) + {(a – b)}] is balanced, while [3 + 2( and { 7 + [ a – b} ] are not balanced.

The method takes as input a mathematical expression and outputs whether the input is balanced or not. Use stacks to find your answer. Test your method on ((3), [(3 + 4)] and {{( )( )}}.

Solutions

Expert Solution

Q2. public static boolean isPalindrome(char str[])
{
int len = str.length;
  
// Allocating the memory for the stack
Stack s = new Stack(40);
  
// Finding the mid
int i, mid = len/ 2;
  
for (i = 0; i < mid; i++)
{
s1. push(str[i]);
}
  
// Checking if the length of the String
// is odd then neglect the
// middle character
if (len % 2 != 0)
{
i++;
}
  
// While not the end of the String
while (i < len)
{
char el = s1.pop();
  
// If the characters differ then the
// given String is not a palindrome
if (el != str[i])
return false;
i++;
}
  
return true;
}

public static Stack  reverse( Stack s1)
{

while (!queue.isEmpty()) {
s1.push(queue.peek());
queue.dequeue();
}
while (!s1.isEmpty()) {
queue.enqueue(s1.peek());
s1.pop();
}
}
  

Q3.

public static boolean isBalanced(String expression)
{
Stack s =new Stack(40);
  
// Traversing the Expression
for (int i = 0; i < expression.length(); i++) {
char z = expression.charAt(i);
  
if (z == '(' || z == '[' || z == '{') {
// Push the element in the stack
s.push(z);
continue;
}
  

if (s.isEmpty())
return false;
  
switch (z) {
case ')':
s.pop();
if (z == '{' || z== '[')
return false;
break;
  
case '}':
s.pop();
if (z == '(' || z == '[')
return false;
break;
  
case ']':
s.pop();
if (z == '(' || z == '{')
return false;
break;
}
}
  
// Check Empty Stack
if (s.isEmpty())

return true;
}
  


Related Solutions

Task Generics: GenericStack Class. Java. package Modul02; public class GenericStack<E> { private java.util.ArrayList<E> list = new...
Task Generics: GenericStack Class. Java. package Modul02; public class GenericStack<E> { private java.util.ArrayList<E> list = new java.util.ArrayList<>(); public int size() { return list.size(); } public E peek() { return list.get(size() - 1); } public void push(E o) { list.add(o); } public E pop() { E o = list.get(size() - 1); list.remove(size() - 1); return o; } public boolean isEmpty() { return list.isEmpty(); } @Override public String toString() { return "stack: " + list.toString(); } } package Modul02; public class TestGenericStack...
In C++ In this lab we will be creating a stack class and a queue class,...
In C++ In this lab we will be creating a stack class and a queue class, both with a hybrid method combining linked list and arrays in addition to the Stack methods(push, pop, peek, isEmpty, size, print) and Queue methods (enqueue, deque, peek, isEmpty, size, print). DO NOT USE ANY LIBRARY, implement each method from scratch. Both the Stack and Queue classes should be generic classes. Don't forget to comment your code.
MAKE node class outside of stack class class Stack{    private:        class node{   ...
MAKE node class outside of stack class class Stack{    private:        class node{            public:                node *next;                int data;                node(int d,node *n = NULL){                    data = d;                    next = n;                }        };        node *start;           public:        Stack();        Stack(const Stack& original);...
Please add comments to this code! JAVA code: import java.util.ArrayList; public class ShoppingCart { private final...
Please add comments to this code! JAVA code: import java.util.ArrayList; public class ShoppingCart { private final ArrayList<ItemOrder> itemOrder;    private double total = 0;    private double discount = 0;    ShoppingCart() {        itemOrder = new ArrayList<>();        total = 0;    }    public void setDiscount(boolean selected) {        if (selected) {            discount = total * .1;        }    }    public double getTotal() {        total = 0;        itemOrder.forEach((order) -> {            total +=...
Define empty methods in Queue class using LinkedList class in Java ------------------------------------------------------------------------------- //Queue class public class...
Define empty methods in Queue class using LinkedList class in Java ------------------------------------------------------------------------------- //Queue class public class Queue{ public Queue(){ // use the linked list } public void enqueue(int item){ // add item to end of queue } public int dequeue(){ // remove & return item from the front of the queue } public int peek(){ // return item from front of queue without removing it } public boolean isEmpty(){ // return true if the Queue is empty, otherwise false }...
Convert the Queue to Generic implementation: public class MyQueueImpl implements MyQueue {    private int capacity;...
Convert the Queue to Generic implementation: public class MyQueueImpl implements MyQueue {    private int capacity;    private int front;    private int rear;    private int[] arr;    public MyQueueImpl(int capacity){        this.capacity = capacity;        this.front = 0;        this.rear = -1;        this.arr = new int[this.capacity];    }    @Override    public boolean enQueue(int v) {                  if(this.rear == this.capacity - 1) {                //Perform shift   ...
Define empty methods in Stack class using LinkedList class in Java ------------------------------------------------------------------------------- //Stack class public class...
Define empty methods in Stack class using LinkedList class in Java ------------------------------------------------------------------------------- //Stack class public class Stack{ public Stack(){ // use LinkedList class } public void push(int item){ // push item to stack } public int pop(){ // remove & return top item in Stack } public int peek(){ // return top item in Stack without removing it } public boolean isEmpty(){ // return true if the Stack is empty, otherwise false } public int getElementCount(){ // return current number...
Q1 A- What are stack and queue? What are the differences between stack and queue? B-...
Q1 A- What are stack and queue? What are the differences between stack and queue? B- What is the priority queue? What are the differences between queue and priority queue
public class StringNode { private String item; private StringNode next; } public class StringLL { private...
public class StringNode { private String item; private StringNode next; } public class StringLL { private StringNode head; private int size; public StringLL(){ head = null; size = 0; } public void add(String s){ add(size,s); } public boolean add(int index, String s){ ... } public String remove(int index){ ... } } In the above code add(int index, String s) creates a StringNode and adds it to the linked list at position index, and remove(int index) removes the StringNode at position...
I have the following code: //Set.java import java.util.ArrayList; public class Set<T> { //data fields private ArrayList<T>...
I have the following code: //Set.java import java.util.ArrayList; public class Set<T> { //data fields private ArrayList<T> myList; // constructors Set(){ myList = new ArrayList<T>(); } // other methods public void add(T item){ if(!membership(item)) myList.add(item); } public void remove(T item){ if(membership(item)) myList.remove(item); } public Boolean membership(T item){ for (T t : myList) if (t.equals(item)) return true; return false; } public String toString(){ StringBuilder str = new StringBuilder("[ "); for(int i = 0; i < myList.size() - 1; i++) str.append(myList.get(i).toString()).append(", "); if(myList.size()...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT