Question

Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped...

Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped everytime instead of the one. If there is only one element in the stack, just pop the one element and report that the stack is now empty. If stack is empty, it should just report that stack is empty. All other functions for StackArray remain the same.

using java

StackArray.java:

public class StackArray {
  
   private final int size = 20; //Size of the stack array
   private int[] elements; //Array that gets created as a stack
   private int topIndex = -1; //index of the top element
  
   public StackArray() {
       elements = new int[size];
   }
  
   public StackArray( int maxSize ) {
       elements = new int[maxSize];
   }
  
   public void push( int element ) {
       if( isFull( ))
           System.out.println("Stack is full and element cannot be pushed");
       //throw new Exception("Stack Full");
       else {
           topIndex++;
           elements[topIndex ] = element;
       }
   }
  
   public void pop() {
       if( isEmpty() )
           System.out.println("Stack is empty and element cannot be popped");
   //throw new Exception("Stack Empty");
       else {
           topIndex--;
       }
   }
  
   public int top() {
       if( isEmpty() ) {
           System.out.println("Stack is empty and no Top exists");
           System.exit(1);
           return 0;
       }
       else
           return elements[topIndex];
      
   }
  
   public boolean isEmpty() {
       return topIndex == -1;
   }
  
   public boolean isFull() {
       return ( topIndex == elements.length - 1 );
      
   }
  
   public void printStack() {
       if( isEmpty())
           System.out.println("Stack is empty");
       else
           for( int i = 0; i <= topIndex; i++)
               System.out.print(elements[i] + " ");
       System.out.println();
      
   }

}

Homework Answers

Answer #1

Theory:

Stack:

-The stack is a linear data structure which obeys the LIFO(Last In First Out) sequence.

Operations on Stack:

There are mainly 2 operations perform on stack:

1.Push- we can add elements in stack using push() method. Its add element to the top of stack.

2.Pop- We can delete elements in stack using pop() method. Its delete top element of stack.

Solution:

Algorithm to pop 2 element at a time from stack:

1. Create a stack.

2. Enter/push some values in stack.

Note: the stack values must be differents.

3. for deleting elements first check the stack is empty or not.

4. If the stack is not empty then we check the first element i.e 0th location of stack is a top element or not.

5. If it is top element then we can delete one element and display stack is empty.

6. If it is not a top element then we can delete two element and continue process.

7.display the stack.

Code:

public class StacktwoPopArr {
  
private final int size = 20; //Size of the stack array
private int[] elements; //Array that gets created as a stack
private int topIndex = -1; //index of the top element
  
public StacktwoPopArr() {
elements = new int[size];
}
  
public StacktwoPopArr( int maxSize ) {
elements = new int[maxSize];
}
  
public void push( int element ) {
if( isFull( ))
System.out.println("Stack is full and element cannot be pushed");
//throw new Exception("Stack Full");
else {
topIndex++;
elements[topIndex ] = element;
}
}
  
public void pop() {
if( isEmpty() )
System.out.println("Stack is empty and element cannot be popped");
//throw new Exception("Stack Empty");
else {
if (elements[0]==elements[topIndex])
{
topIndex--;
System.out.println("Stack is empty");
}
else
{
topIndex--;
topIndex--;
}
}
}

  
public int top() {
if( isEmpty() ) {
System.out.println("Stack is empty and no Top exists");
System.exit(1);
return 0;
}
else
return elements[topIndex];
  
}
  
public boolean isEmpty() {
return topIndex == -1;
}
  
public boolean isFull() {
return ( topIndex == elements.length - 1 );
  
}
  
public void printStack() {
if( isEmpty())
System.out.println("Stack is empty");
else
for( int i = 0; i <= topIndex; i++)
System.out.print(elements[i] + " ");
System.out.println();
  
}
public static void main(String[] args) {
StacktwoPopArr s=new StacktwoPopArr();
s.push(10); //call push() method for adding element
s.printStack();// the output: 10
s.push(20);
s.printStack();// the output: 10 20
s.push(30);
s.printStack();// the output: 10 20 30
s.pop();//In this line we delete top 2 elements i.e 30 and 20
s.printStack();// the output: 10
s.pop();//In this line we delete remaining one element i.e 10 and print stack is empty.
}
}

Output:

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {    public static final int DEFAULT_SIZE = 10;    private Object data[];    private int index; code 2 package test; import java.util.*; /* Class Node */ class Node { protected Object data; protected Node link; /* Constructor */ public Node() { link = null; data = 0; } /* Constructor */ public Node(Object d,Node n) { data = d; link = n; } /*...
(JAVA) Why is my toString method not printing out the last node? It will not print...
(JAVA) Why is my toString method not printing out the last node? It will not print out "A" which is for Alice. Everything else is working just fine except for this. package driver; import exception.StackException; import stack.*; public class StackDriver { public static void main(String[] args) throws Exception { StackInterface<Painting> painting = new LinkedStack <Painting>(); try { System.out.println("Peeking at top of player stack.\n" + painting.peek()); }catch (StackException e) { System.out.println(e); System.out.println("Let's double check if it's empty: " + painting.isEmpty()); }...
Q: Implement an equals method for the ADT list that returns true when the entries in...
Q: Implement an equals method for the ADT list that returns true when the entries in one list equal the entries in a second list. In particular, add this method to the class AList. The following is the method header: public boolean equals (Object other) public class AList<T>{ private T list[]; private int capacity = 100; private int numOfEnteries =0; public AList(){ list = (T[])new Object[capacity + 1]; } public void add(T element){ numOfEnteries++; if (numOfEnteries >capacity) System.out.println ("Exceed limit");...
- implement the Stack ADT using the linked list approach. Use C++ program language #include "StackLinked.h"...
- implement the Stack ADT using the linked list approach. Use C++ program language #include "StackLinked.h" template StackLinked::StackLinked (int maxNumber) { } template StackLinked::StackLinked(const StackLinked& other) { } template StackLinked& StackLinked::operator=(const StackLinked& other) { } template StackLinked::~StackLinked() {    clear(); } template void StackLinked::push(const DataType& newDataItem) throw (logic_error) {    } template DataType StackLinked::pop() throw (logic_error) { } template void StackLinked::clear() {    StackNode* t;    while ( top != NULL)    {        t = top;       ...
Using SLLStack.java, implement an application, LineReverser.java, that reads a line from keyboard (user enters one line),...
Using SLLStack.java, implement an application, LineReverser.java, that reads a line from keyboard (user enters one line), insert each separate word into the stack, and read/print on the screen. So, if the user enters: This is a test the application output should be: test a is This. This is SLLSTACK.java below package linked_lists; public class SLLStack {    //instance variabels    private SLLNode top;    private int numOfItems;       //constructors    public SLLStack() {        top = null;   ...
In the attached FlexArray Java class, implement a method public int delete (int location) { }...
In the attached FlexArray Java class, implement a method public int delete (int location) { } that deletes the integer value stored at location in the array, returns it, and ensures that the array values are contiguous.  Make sure to handle the array empty situation.  What is the time-complexity of the method, if the array size is n. ***************************************************************************************************************************** public class FlexArray { int [] array; private int size; private int capacity; public FlexArray() { capacity=10; size=0; array=new int[10]; } public FlexArray(int...
Use Java: Also: Please include screenshots if possible. Create a class called AbstractStackTest. Write an abstract...
Use Java: Also: Please include screenshots if possible. Create a class called AbstractStackTest. Write an abstract method called makeStack that returns a Stack of Strings. Use the Stack interface as the return type, not a specific implementation! Write a class named NodeStackTest that extends your AbstractStackTest class. Implement the makeStack method to return a NodeStack. Repeat parts 1 and 2 for the Queue interface and the NodeQueue implementation. Write a new stack implementation, ArrayStack. It should be generic and use...
The AssemblyLine class has a potential problem. Since the only way you can remove an object...
The AssemblyLine class has a potential problem. Since the only way you can remove an object from the AssemblyLine array is when the insert method returns an object from the last element of the AssemblyLine's encapsulated array, what about those ManufacturedProduct objects that are "left hanging" in the array because they never got to the last element position? How do we get them out? So I need to edit my project. Here is my AssemblyLine class: import java.util.Random; public class...
I'm having a warning in my visual studio 2019, Can anyone please solve this warning. Severity  ...
I'm having a warning in my visual studio 2019, Can anyone please solve this warning. Severity   Code   Description   Project   File   Line   Suppression State Warning   C6385   Reading invalid data from 'DynamicStack': the readable size is '(unsigned int)*28+4' bytes, but '56' bytes may be read.   Here is the C++ code were I'm having the warning. // Sstack.cpp #include "SStack.h" // Constructor SStack::SStack(int cap) : Capacity(cap), used(0) {    DynamicStack = new string[Capacity]; } // Copy Constructor SStack::SStack(const SStack& s) : Capacity(s.Capacity), used(s.used)...
This is the java code that I have, but i cannot get the output that I...
This is the java code that I have, but i cannot get the output that I want out of it. i want my output to print the full String Form i stead of just the first letter, and and also print what character is at the specific index instead of leaving it empty. and at the end for Replaced String i want to print both string form one and two with the replaced letters instead if just printing the first...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT