Question

Unsure as to how I would be able to have an array behave as a stack...

Unsure as to how I would be able to have an array behave as a stack in java by removing the last (top) element of an array as well as pushing a new element into the top to the top of the stack. All without using any packages.

Homework Answers

Answer #1

/* ARRAY IMPLEMENTATION OF STACK */

import java.util.*;

class Stack
{
   private int arr[];
   private int top;
   private int capacity;

   // Constructor to initialize stack
   Stack(int size)
   {
       arr = new int[size];
       capacity = size;
       top = -1;
   }

   // Utility function to add an element x in the stack
   public void push(int x)
   {
       if (isFull())
       {
           System.out.println("OverFlow\nProgram Terminated\n");
           System.exit(1);
       }

       System.out.println("Inserting " + x);
       arr[++top] = x;
   }

   // Utility function to pop top element from the stack
   public int pop()
   {
       // check for stack underflow
       if (isEmpty())
       {
           System.out.println("UnderFlow\nProgram Terminated");
           System.exit(1);
       }

       System.out.println("Removing " + peek());

       // decrease stack size by 1 and (optionally) return the popped element
       return arr[top--];
   }

   // Utility function to return top element in a stack
   public int peek()
   {
       if (!isEmpty())
           return arr[top];
       else
           System.exit(1);

       return -1;
   }

   // Utility function to return the size of the stack
   public int size()
   {
       return top + 1;
   }

   // Utility function to check if the stack is empty or not
   public Boolean isEmpty()
   {
       return top == -1;   // or return size() == 0;
   }

   // Utility function to check if the stack is full or not
   public Boolean isFull()
   {
       return top == capacity - 1;   // or return size() == capacity;
   }

   public static void main (String[] args)
   {
       Stack stack = new Stack(3);

       stack.push(1);       // Inserting 1 in the stack
       stack.push(2);       // Inserting 2 in the stack

       stack.pop();       // removing the top 2
       stack.pop();       // removing the top 1

       stack.push(3);       // Inserting 3 in the stack

       System.out.println("Top element is: " + stack.peek());
       System.out.println("Stack size is " + stack.size());

       stack.pop();       // removing the top 3

       // check if stack is empty
       if (stack.isEmpty())
           System.out.println("Stack Is Empty");
       else
           System.out.println("Stack Is Not Empty");
   }
}

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
1.A stack implemented with an array has what performance? Select one: a. O(n3) b. O(n log...
1.A stack implemented with an array has what performance? Select one: a. O(n3) b. O(n log n) c. O(n) d. O(n2) 2. A stack uses the first in first out insertion and deletion method. Select one: True False 3. Match the following stack operations with their meaning. object pop(); boolean isEmpty(); push (object); integer size(); object top(); meanings are: - returns the number of elements stored -just removes the last inserted elements - returns the last inserted elements without removing...
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...
In five sentences describe the following: a) how you would implement a stack using an array,...
In five sentences describe the following: a) how you would implement a stack using an array, including the push and pop operation b) how you could implement a queue using a linked list, including what type of linked list would be best, the enqueue and dequeue operations
1. Given an n-element array A, Algorithm X executes an O(n)-time computation for each even number...
1. Given an n-element array A, Algorithm X executes an O(n)-time computation for each even number in A and an O(log n)-time computation for each odd number in A. What is the best-case running time of Algorithm X? What is the worst-case running time of Algorithm X? 2. Given an array, A, of n integers, give an O(n)-time algorithm that finds the longest subarray of A such that all the numbers in that subarray are in sorted order. Your algorithm...
I have an object struct named Course. I also have an array Course array[CAPACITY], where capacity...
I have an object struct named Course. I also have an array Course array[CAPACITY], where capacity = 100 and the size is 0. I do not know how to place the four attributes of object Course into an array and I was hoping to get an answer. I am using a for loop that takes in the class name, year, grade, and units, so how can I put that all into a Course object and then into an array of...
Phys1011: Atomic Physics :i have these labs without any text book or handouts assigned. i would...
Phys1011: Atomic Physics :i have these labs without any text book or handouts assigned. i would love some insight and help so that i can learn the concepts better and prep for tests thru this. In this simulation lab, we will look at different models of the hydrogen atom that attempt to explain observations of photons interacting with elemental hydrogen. This is a Java simulation from PhET. Please contact your instructor if you have trouble accessing the simulation. This lab...
Java : Modify the selection sort algorithm to sort an array of integers in descending order....
Java : Modify the selection sort algorithm to sort an array of integers in descending order. describe how the skills you have gained could be applied in the field. Please don't use an already answered solution from chegg. I've unfortunately had that happen at many occasion ....... ........ sec01/SelectionSortDemo.java import java.util.Arrays; /** This program demonstrates the selection sort algorithm by sorting an array that is filled with random numbers. */ public class SelectionSortDemo { public static void main(String[] args) {...
Microsoft Visual Studio in C#: I have this code and need to loop through each element...
Microsoft Visual Studio in C#: I have this code and need to loop through each element of the patient's array and add to a listbox (lbAccountDisplay) each property of the patient's object. This is the 2nd time to ask this question; it should have all the detail you need to help me. It is a piece of a project and I am trying not to give you the whole project. How do I use a foreach loop to loop through...
I have done these problems but am unsure if the answers I got were correct, Please...
I have done these problems but am unsure if the answers I got were correct, Please show all steps so I can fully understand! 1.) How many microliters of original sample are required to produce a final dilution of 10-3 in a total volume of 1 mL?       INFO: 1 microliter is 10-6 L or 10-3 mL. 2.) If you suspect your culture of bacteria has 240 x 106 cells per mL, what would you want the final dilution to be...
I would like to know how to implement the extended euclidean algorithm in Java which takes...
I would like to know how to implement the extended euclidean algorithm in Java which takes 2 integers, public int xgcd(int a, int b) and returns the multiplicative inverse of 'a' modulo 'b' and if the multiplicative inverse of 'a' does not exist it should return -1. I know to do it in a recursive manner but I need help with the non-recursive or iterative manner without using biginteger.math. Something like using the pseudocode would do. I would really appreciate...