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; } /*...
Given main() complete the Stack class by writing the methods push() and pop(). The stack uses...
Given main() complete the Stack class by writing the methods push() and pop(). The stack uses an array of size 5 to store elements. The command Push followed by a positive number pushes the number onto the stack. The command Pop pops the top element from the stack. Entering -1 exits the program. Ex. If the input is Push 1 Push 2 Push 3 Push 4 Push 5 Pop -1 the output is Stack contents (top to bottom): 1 Stack...
(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;       ...
class Car{ private String make; public Car(String make){ this.make = make; } public String toString(){ return...
class Car{ private String make; public Car(String make){ this.make = make; } public String toString(){ return make; } } class Node<T>{ public T data; public Node next; public Node(T data){ this.data = data; this.next = null; } } public class StackLinkedList<T>{ //Single field of type Node    //to represent the front of the stack //operation push() /* The push operation is equivalent to the inserting a node at the head of the list. */ public void push(T data){ } //operation...
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;   ...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue class . Call your class Queue. it must be a template class. public class Queue { } I have put a driver program in the module . It is called CircularQueue.java This driver program should then run with your Queue class (no modifications allowed to the driver program). Your Queue class should have at least the following methods: one or more constructors, enqueue, dequeue,...
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...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT