Dynamic Implementation of Stack -
The purpose is to use our dynamic implementation of stack. The application will be to add large numbers.
Review adding large numbers
Remember that we can use stacks to safely add integer values that overflow the int data type
Using stacks to add large numbers safely
Will actually represent the large integers to be added as strings of characters, to avoid any overflow problems here. Then will use three(!) stacks of datatype Integer to do the addition safely.
The idea is to add each pair of digits from the numbers, from right to left. The units part of this total is pushed to the results stack, the tens part is the carry digit, added in to the next pair.
The addition algorithm in pseudocode is something like:
//push digits from numbers into stacks in appropriate order loop for the digits in the first number push digit to first stack loop for the digits in the second number push digit to second stack //pop stacks, add digits and push result to result stack. Careful with carry while (!stacks are empty) pop digits from stacks and add push units part to result stack tens part is the carry to be added in next iteration //print the result from the result stack while (!result stack is empty) pop result stack
Open the project and see Tester::main(). You must write code in the Tester::main() method that uses the stack implementation to add the pairs of numbers given.
Format your output so that it shows the first and second numbers, and your result (I've used '?' below to show where your result will go). Run your program three times to test each of the pairs of numbers provided e.g.
1 + 2147483647 = ? 2147483647 + 1 = ? 2147483647 + 2147483647 = ?
public class Tester
{
public static void main()
{
//first shorter
String first = "1";
String second = "2147483647";
//second shorter
//String first = "2147483647";
//String second = "1";
//same length
//String first = "2147483647";
//String second = "2147483647";
//you must write all of your code here
}
}
public class StackUnderflowException extends
RuntimeException
{
public StackUnderflowException()
{
super();
}
public StackUnderflowException(String message)
{
super(message);
}
}
public class LinkedStack<T> implements
StackInterface<T>
{
private Item<T> top;
public LinkedStack()
{
top = null;
}
public void push(T element)
{
Item<T> item = new Item<T>(element);
if (!isEmpty())
item.next = top;
top = item;
}
public T pop() throws StackUnderflowException
{
if (isEmpty())
throw new StackUnderflowException("Pop attempted on empty
stack");
else {
T info = top.info;
top = top.next;
return info;
}
}
public boolean isEmpty()
{
return top == null;
}
}
public interface StackInterface<T>
{
void push(T element);
T pop() throws StackUnderflowException;
boolean isEmpty();
}
public class Item<T>
{
protected T info;
protected Item<T> next;
public Item()
{
info = null;
next = null;
}
public Item(T info)
{
this.info = info;
next = null;
}
}
:: solution ::
public static void main(String []args){
String first = "2147483647";
String second = "2147483647";
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
int len1 = first.length();
int len2 = second.length();
int duplen1 = len1;
int duplen2 = len2;
while(len1>0 || len2>0){
if(len1>0){
stack1.push(first.charAt(duplen1-len1)-'0');
len1--;
}
if(len2>0){
stack2.push(second.charAt(duplen2-len2)-'0');
len2--;
}
}
String res = "";
int carry = 0;
while(!stack1.isEmpty() || !stack2.isEmpty()){
int firstDigit = (stack1.isEmpty())?0:stack1.pop();
int secondDigit = (stack2.isEmpty())?0:stack2.pop();
if(carry+firstDigit+secondDigit >= 10){
res = (carry+firstDigit+secondDigit-10)+res;
carry = 1;
}
else{
res = (carry+firstDigit+secondDigit)+res;
carry = 0;
}
}
if(carry==1){
res = 1+res;
}
System.out.println("sum of numbers "+first+" and "+second+" = "+res);
}
I have provide you the main function with code.
And also provided the screenshots of the inputs you provided for testing.
Hope you like it.
Dynamic Implementation of Stack - The purpose is to use our dynamic implementation of stack. The...
Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns a value of primitive type int equal to the number of items on the stack. The method signature for sizeIS is public int sizeIs() a.) Write the code for sizeIs for the ArrayStack class b.) Write the code for sizeIs for the LinkedStack class (do not add any instance variables to the class; each time sizeIs is called you must "walk" through the stack...
Java - data structures Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations. Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows: The first new method checks whether we should reduce the...
I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT with the implementation of your choice (Array or Link), it should not make a difference 2.Read two “integer” numbers from the user. Hint: You don’t need to use an int type when you read, it may be easier to parse the input...
Use the following implementation of LinkedListNode to write the Stack4T> classi public class LinkListNodecT>T private T info; private LinkListNode link; public LinkListNode ( T info) this, info = info; link = null; public T getInfo() return info; public LinkListNode getlink() return link; public void setInfo( T info) this.infoinfo; public void setLink (LinklistNode link) this.link = link; public interface StackInterface <T T top() throws StackUnderflowException; void pop () throws StackUnderflowException; void push (T element);
Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException at InfixExpression.execute(InfixExpression.java:98) at InfixExpression.Evaluate(InfixExpression.java:65) at InfixExpression.setWholeExpr(InfixExpression.java:24) at InfixExpression.<init>(InfixExpression.java:17) at Main.testHW1(Main.java:17) at Main.main(Main.java:6)" I need to get this as my output: "Testing InfixExpression: When passing null, the String and double = Infix String: , result: 0.0 When passing a valid String, the String and double = Infix String: ( 234.5 * ( 5.6 + 7.0 ) ) / 100.2, result: 29.488023952095805 ..." I...
Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of the peek, isEmpty, size, and toString methods. See Base_A06Q1.java for a starting place and a description of these methods. Here is the base given: /** * Write a description of the program here. * * @author Lewis et al., (your name) * @version (program version) */ import java.util.Iterator; public class Base_A06Q1 { /** * Program entry point for stack testing. * @param args Argument...
Recursively sorting an unbounded stack (java) in ascending order? (This assignment is only limited to stacks only, No other data structures are allowed) My professor gave us a hint on how to implement this, however she wants the comparable interface to be used. im not sure on how to do this. Hint: May want to use a public method that accepts the original stack and then creates the two additional stacks needed. This method then calls a private method that...
There is a data structure called a drop-out stack that behaves like a stack in every respect except that if the stack size is n, then when the n+1element is pushed, the bottom element is lost. Implement a drop-out stack using links, by modifying the LinkedStack code. (size, n, is provided by the constructor. Request: Please create a separate driver class, in a different file, that tests on different types of entries and show result of the tests done on...
Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix) { LinkedStack stack2 = new LinkedStack(); int val1; int val2; int result; for(int i = 0; i < postFix.length(); i++) { char m = postFix.charAt(i); if(Character.isDigit(m)) { stack2.push(m); } else { ...
Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods: peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...