Question

10.6 LAB: Implement a stack using an array Given main() complete the Stack class by writing...

10.6 LAB: Implement a stack using an array

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 contents (top to bottom):
2
1

Stack contents (top to bottom):
3
2
1

Stack contents (top to bottom):
4
3
2
1

Stack contents (top to bottom):
5
4
3
2
1

Stack contents (top to bottom):
4
3
2
1

PushPopStack.java

import java.util.Scanner;

public class PushPopStack {

public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
Stack stack = new Stack(5);
String action; // Push or Pop   
int numInput; // Integer value to push

action = scnr.next();

while (!action.equals("-1")) {
if (action.equals("Push")) {
numInput = scnr.nextInt();
stack.push(numInput);
System.out.println("Stack contents (top to bottom):");
stack.printStack();
}
else if (action.equals("Pop")) {
stack.pop();
System.out.println("Stack contents (top to bottom):");
stack.printStack();
}

action = scnr.next();
}
}
}

Stack.java

public class Stack {
  
private int topElement;
int size;
int [] array;

public Stack(int arraySize) {
size = arraySize;
array = new int[size];
topElement = -1;
}

// TODO: Write a method to push a value into the stack


// TODO: Write a method to pop the top value from the stack   


public void printStack() {
int i;
  
for(i = topElement; i >= 0; --i) {
System.out.println(array[i]);
}
System.out.println();
}
}

Homework Answers

Answer #1
public class Stack {

    private int topElement;
    int size;
    int[] array;

    public Stack(int arraySize) {
        size = arraySize;
        array = new int[size];
        topElement = -1;
    }

    public void push(int num) {
        if (topElement < size - 1) {
            array[topElement + 1] = num;
            topElement++;
        }
    }

    public int pop() {
        if (topElement > -1) {
            int result = array[topElement];
            topElement--;
            return result;
        } else {
            return -1;
        }
    }

    public void printStack() {
        int i;

        for (i = topElement; i >= 0; --i) {
            System.out.println(array[i]);
        }
        System.out.println();
    }
}
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
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...
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...
Instructions: SLLStack (12 pts) ● Using the two properties below, implement the stack interface using the...
Instructions: SLLStack (12 pts) ● Using the two properties below, implement the stack interface using the SLLNode class from Lab 2: ○ top_node → SLLNode object or None ○ size → int, keep track of stack size ● Implement the push( ), pop( ), top( ) methods ● Use SLLNode methods: get_item( ), set_item( ), get_next( ), set_next( ) ● (5 pts) In push(item): ○ Create new SLLNode with item ○ Add new node before top node ○ Update top_node...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        }        int new_k = scan.nextInt(); System.out.println(""+smallerK(new_stack, new_k));    }     public static int smallerK(Stack s, int k) {       ...
ex3 Write a method public static boolean isPalindrome(String input) that uses one or more stacks to...
ex3 Write a method public static boolean isPalindrome(String input) that uses one or more stacks to determine if a given string is a palindrome. [A palindrome is a string that reads the same forwards and backwards, for example ‘racecar’, ‘civic’]. Make sure that your method works correctly for special cases, if any. What is the big-O complexity of your method in terms of the list size n. Supplementary Exercise for Programming (Coding) [Stacks] Download and unpack (unzip) the file Stacks.rar....
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...
Complete the // TODO sections in the EasyRental class. Create a method that implements an iterative...
Complete the // TODO sections in the EasyRental class. Create a method that implements an iterative sort that sorts the vehicle rentals by color in ascending order (smallest to largest) Create a method to binary search for a vehicle based on a color, that should return the index where the vehicle was found or -1 You are comparing Strings in an object not integers. Ex. If the input is: brown red white blue black -1 the output is: Enter the...
import java.util.Scanner; public class FindMinLength { public static int minLength(String[] array) { int minLength = array[0].length();...
import java.util.Scanner; public class FindMinLength { public static int minLength(String[] array) { int minLength = array[0].length(); for (int i = 0; i < array.length; i++) { if (array[i].length() < minLength) minLength = array[i].length(); } return minLength; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] strings = new String[50]; for (int i = 0; i < strings.length; i++) { System.out.print("Enter string " + (i + 1) + ": "); strings[i] = in.nextLine(); } System.out.println("Length of smallest...
Complete the following C program to solve the parenthesis matching problem using a stack. We studied...
Complete the following C program to solve the parenthesis matching problem using a stack. We studied the problem and the algorithm in class. Given a sequence of chars (symbols), check if each “(”, “{”, or “[” is paired with a matching “)”, “}”, or “[”. For example, correct: ( )(( )){([( )])}     correct: (( )(( ))){([( )])}   incorrect: )(( )){([( )])}     incorrect: ({[ ])}     incorrect: (   #include <stdio.h> #include <stdlib.h> #define size 100 void push(char *s, int* top, char element);...
- 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;       ...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT