Question

In: Computer Science

Please hurry, will upvote if correct! This is the problem in Java: [(1)] A palindrome is...

Please hurry, will upvote if correct!

This is the problem in Java:

[(1)] A palindrome is a string that reads the same forwards as backwards. Using only a fixed number of stacks and queues, the stack and queue ADT functions, and a fixed number of int and char variables, write an algorithm to determine if a string is a palindrome. Assume that the string is read from standard input one character at a time. The algorithm should output true or false as appropriate

[(2)] Let Q be a non-empty queue, and let S be an empty stack. Using only the stack and queue ADT functions and a single element variable X, write an algorithm to reverse the order of the elements in Q.

[(3)] Use singly linked lists to implement integers of unlimited size. Each node of the list should store one digit of the integer. You should implement addition, subtraction, multiplication, and exponentiation operations. Limit exponents to be positive integers. What is the asymptotic running time for each of your operations, expressed in terms of the number of digits for the two operands of each function?

[(4)] Implement a program that can input an expression in postfix notation and output its value.

I have working code (below), but please check that the above conditions are met and implement parts 2 and 3 as necessary, keeping number 4 in mind.

import java.io.*;
import java.util.Stack;
import java.util.LinkedList; //libraries required
import java.util.Queue;
import java.util.Scanner;


public class Palindrome{


   public static boolean check_Palindrome(String str){ //method to check if the given string is palindrome or not

       Queue queue = new LinkedList(); //declaring the queue

       Stack stack = new Stack(); //declaring the stack

       Character alphabet;

       int count = 0;
  
   for (int i = 0; i < str.length(); i++){
             
           alphabet = str.charAt(i);   

           queue.add(alphabet); //add each character to the queue and the stack

           stack.push(alphabet);
          
   }
      
       while (!queue.isEmpty()){
             
           if (queue.remove()!=stack.pop()) //removal of each character from queue and stack must be same to say it's palindrome
               count++;
      
       }

       if(count==0) //if the count equal to zero then it is a palindrome
           return true;
       else
           return false;
   }


   public static void main(String[] args) {

       String str;

       Scanner sc = new Scanner(System.in);

       System.out.print("Enter the string : "); //taking string from user

       str = sc.nextLine();

      
       if(check_Palindrome(str))
           System.out.println("True");
      
       else
           System.out.println("False");


      
   }

}

Solutions

Expert Solution

1) The algorithm for checking if a string is a palindrome using stack data structure functions are:

· Find the length of the string say len. Now, find the mid as mid = len / 2.

· Push all the elements till mid into the stack i.e. str[0…mid-1].

· If the length of the string is odd then neglect the middle character.

· Till the end of the string, keep popping elements from the stack, and compare it with the current character i.e. string[i].

· If there is a mismatch then the string is not a palindrome. If all the elements match then the string is a palindrome.

2) For reversing the queue one approach could be to store the elements of the queue in a temporary data structure in a manner such that if we re-insert the elements in the queue they would get inserted in reverse order. Since stack works on the LIFO paradigm, this can be done using a stack. This will be a two-step process:

  • Pop the elements from the queue and insert them into the stack. (Topmost element of the stack is the last element of the queue)
  • Pop the elements of the stack to insert back into the queue. (The last element is the first one to be inserted into the queue.

3) For the above problem we will simply use a self-made Singly linked list data structure implementation.

CODE:

//This program will add, subtract and multiply two lists

//Lists are defined inside the program

class LinkedList

{

    static Node head1, head2;

    static class Node {

        int data;

        Node next;

        Node(int d) {

            data = d;

            next = null;

        }

    }

    /* Adds contents of two linked lists and return the head node of resultant list */

    Node addTwoLists(Node first, Node second) {

        Node res = null; // res is head node of the resultant list

        Node prev = null;

        Node temp = null;

      int carry = 0, sum;

        while (first != null || second != null) //while both lists exist

        {

            sum = carry + (first != null ? first.data : 0)

                    + (second != null ? second.data : 0);

            // update carry for next calulation

            carry = (sum >= 10) ? 1 : 0;

            // update sum if it is greater than 10

            sum = sum % 10;

            // Create a new node with sum as data

            temp = new Node(sum);

            // if this is the first node then set it as head of

            // the resultant list

            if (res == null) {

                res = temp;

            } else // If this is not the first node then connect it to the rest.

            {

                prev.next = temp;

            }

            // Set prev for next insertion

            prev = temp;

            // Move first and second pointers to next nodes

            if (first != null) {

                first = first.next;

            }

            if (second != null) {

                second = second.next;

            }

        }

        if (carry > 0) {

            temp.next = new Node(carry);

        }

        // return head of the resultant list

        return res;

    }

    //function to subtract given lists

    Node subtract(Node first, Node second, int borrow) {

        Node result = new Node(borrow);

        int value = borrow;

        //return null when both list are null

        if (first == null && second == null && borrow == 0)

            return null;

        if (first.data >= second.data) {

            value += first.data - second.data;

            borrow = 0;

        } else {

            if (first.next != null) {

                value += (first.data) + 10 - second.data;

                borrow = -1;

            } else {

                value += (first.data) + 10 - second.data;

                value = value * (-1);

                borrow = 0;

            }

        }

        result.data = value;

        //Recurse

        if (first.next != null || second.next != null || borrow < 0) {

            Node more = subtract(first.next != null ? first.next : null,

                    second.next != null ? second.next : null,

                    borrow < 0 ? -1 : 0);

            result.next = more;

        }

        return result;

    }

    //function to convert list into number

    static int getNumber(Node list) {

        int number = 0;

        while (list != null) {

            number = 10 * number + list.data;

            list = list.next;

        }

        return number;

    }

    //function to traverse a list

    static Node process(Node list) {

        Node head = list;

        int carry = 0, i = 0;

        while (head != null && head.next != null) {

            i = head.data;

            head.data = (carry + i) % 10;

            carry = (i + carry) / 10;

            head = head.next;

        }

        head.data = head.data + carry;

        return reverse(list);

    }

    //function to reverse the given list

    static Node reverse(Node list) {

        if (list == null)

            return null;

        Node current = list, previous = null, forward;

        while (current != null) {

            forward = current.next;

            current.next = previous;

            previous = current;

            current = forward;

        }

        return previous;

    }

    static Node multiply(Node first, Node second) {

        //When both lists are null, return null

        if (first == null || second == null)

            return null;

        int number = getNumber(first); //convert one list into number

        //traverse the second list and multiply the number with the current element of the list and store in the new list.

        Node current = second;

        Node result = null;

        while (current != null) {

            if (result == null) {

                result = new Node(current.data * number);

            } else {

                //multiply current element with the "number" and store in the new list node

                Node temp = new Node(current.data * number);

                temp.next = result;

                result = temp;

            }

            current = current.next;

        }

        return process(result);

    }

    /*function to print a linked list */

    void printList(Node head) {

        while (head != null) {

            System.out.print(head.data + " ");

            head = head.next;

        }

        System.out.println("");

    }

    public static void main(String[] args) {

        LinkedList list = new LinkedList();

        // creating first list

        list.head1 = new Node(7);

        list.head1.next = new Node(5);

        list.head1.next.next = new Node(9);

        list.head1.next.next.next = new Node(4);

        list.head1.next.next.next.next = new Node(6);

        System.out.print("First List is ");

        list.printList(head1);

        // creating seconnd list

        list.head2 = new Node(8);

        list.head2.next = new Node(4);

        list.head2.next.next = new Node(8);

        list.head2.next.next.next = new Node(4);

        list.head2.next.next.next.next = new Node(4);

        System.out.print("Second List is ");

        list.printList(head2);

        // add the two lists and see the result

        Node add = list.addTwoLists(head1, head2);

        System.out.print("\r\nResultant List after Addition is : ");

        list.printList(add);

        Node sub = list.subtract(head1, head2, 0);

        System.out.print("\r\nResultant List after Substraction is : ");

        list.printList(sub);

        Node multiply = list.multiply(head1, head2);

        System.out.print("\r\nResultant List after Multiplication is : ");

        list.printList(multiply);

    }

}

Output:

4)

CODE:

#include<bits/stdc++.h>

using namespace std;
float scanNum(char ch) {
int value;
value = ch;
return float(value-'0'); //return float from character
}
int isOperator(char ch) {
if(ch == '+'|| ch == '-'|| ch == '*'|| ch == '/' || ch == '^')
return 1; //character is an operator
return -1; //not an operator
}
int isOperand(char ch) {
if(ch >= '0' && ch <= '9')
return 1; //character is an operand
return -1; //not an operand
}
float operation(int a, int b, char op) {
//Perform operation
if(op == '+')
return b+a;
else if(op == '-')
return b-a;
else if(op == '*')
return b*a;
else if(op == '/')
return b/a;
else if(op == '^')
return pow(b,a); //find b^a
else
return INT_MIN; //return negative infinity
}
float postfixEval(string postfix) {
int a, b;
stack<float> stk;
string::iterator it;
for(it=postfix.begin(); it!=postfix.end(); it++) {
//read elements and perform postfix evaluation
if(isOperator(*it) != -1) {
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
stk.push(operation(a, b, *it));
}else if(isOperand(*it) > 0) {
stk.push(scanNum(*it));
}
}
return stk.top();
}

int main() {
string postfix;
cout<<"Enter the postfix expression.\n";
cin>>postfix;
cout << "The result is: "<<postfixEval(postfix);
return 0;
}

Output:


Related Solutions

Java Palindrome (Timelimit: 10seconds) Problem Description Write a Java program to solve the following problem. A...
Java Palindrome (Timelimit: 10seconds) Problem Description Write a Java program to solve the following problem. A palindromic number is an integer that is the same when the digits are reversed. For example, 121 and 625526 are palindromic, but 625 is not a palindromic number. Input: The input is in ‘palindrome.txt’. The first line of the input contains the line count m (1 ≤ m ≤ 1,000), which is the number of lines that follows the first line. Each of the...
Please answer this question with explanation. I will upvote your answer if it is correct and...
Please answer this question with explanation. I will upvote your answer if it is correct and clear. Thank you! You are given a positive integer n of the form n = 2h − 1, for some integer h ≥ 1. Give an example of an array of length n where the following method of building a heap step 1. Place the new key at the first free leaf step 2. The heap-order property might be violated: perform a bubble-up, uses...
Java and please have screenshots with source code and output \item[(1)] A palindrome is a string...
Java and please have screenshots with source code and output \item[(1)] A palindrome is a string that reads the same forwards as backwards. Using only a fixed number of stacks and queues, the stack and queue ADT functions, and a fixed number of int and char variables, write an algorithm to determine if a string is a palindrome. Assume that the string is read from standard input one character at a time. The algorithm should output true or false as...
Intro to java Problem, Please provide code and Pseudocode. Not able to compile correct numbers. Problem...
Intro to java Problem, Please provide code and Pseudocode. Not able to compile correct numbers. Problem 7: Simple Calculator (10 points) (General) Calculators represent the most basic, general-purpose of computing machines. Your task is to reduce your highly capable computer down into a simple calculator. You will have to parse a given mathematical expression, and display its result. Your calculator must support addition (+), subtraction (-), multiplication (*), division (/), modulus(%), and exponentiation (**). Facts ● Mathematical expressions in the...
(Using Java) create a class that can identify a palindrome. A palindrome is defined as -...
(Using Java) create a class that can identify a palindrome. A palindrome is defined as - A string of characters that reads the same from left to right as its does from right to left - Example: Anna, Civic, Kayak, Level, Madam - To recognize a palindrome, a queue can be used in conjunction with a stack o A stack can be used to reverse the order of occurrences o A queue can be used to preserve the order of...
Need IN JAVA Please DO NOT COPY AND PASTE old solutions WILL UPVOTE The Babysitters Club...
Need IN JAVA Please DO NOT COPY AND PASTE old solutions WILL UPVOTE The Babysitters Club Employment Agency has decided to computerize their payroll. A babysitter earns a specific fee per hour until 9:00 PM (while the children are awake and active), a lower rate between 9:00 PM and midnight (after bedtimes and the babysitter can study), and a higher fee after midnight (when babysitting cuts into prime sleeping time). They maintain two datafiles are one for the employees and...
IN JAVA - [(1)] A palindrome is a string that reads the same forwards as backwards....
IN JAVA - [(1)] A palindrome is a string that reads the same forwards as backwards. Using only a fixed number of stacks and queues, the stack and queue ADT functions, and a fixed number of int and char variables, write an algorithm to determine if a string is a palindrome. Assume that the string is read from standard input one character at a time. The algorithm should output true or false as appropriate [(2)] Let Q be a non-empty...
In C++: This is the problem: [(1)] A palindrome is a string that reads the same...
In C++: This is the problem: [(1)] A palindrome is a string that reads the same forwards as backwards. Using only a fixed number of stacks and queues, the stack and queue ADT functions, and a fixed number of int and char variables, write an algorithm to determine if a string is a palindrome. Assume that the string is read from standard input one character at a time. The algorithm should output true or false as appropriate [(2)] Let Q...
Create using Java Description: Palindrome -- According to wikipedia "A palindrome is a word, phrase, number...
Create using Java Description: Palindrome -- According to wikipedia "A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction" Write a application that can determine if a 5 digit number you input is a palindrome. If the number is a palindrome then print "The number is a palindrome." If it is not then print "The number is NOT a palindrome" Make sure to use an array Allow input...
Java Palindrome Use StringBuilder concept to create a palindrome checker.   Method should be called pCheck. Must...
Java Palindrome Use StringBuilder concept to create a palindrome checker.   Method should be called pCheck. Must use var-arg concept.   Class name for this program is Palindrome.   Must pass this test:: public class PalindromeTest { public static void main(String[] args) { Palindrome palindrome = new Palindrome(); boolean answer = palindrome.pCheck("racecar", "Bell", "elle", "bunny"); System.out.println(“These are palindromes: " + answer); } }
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT