Extra Credit: The following Java code implements a Stack using an ArrayList. Write a method "peek", that returns the String at the top of the Stack without removing the String from the Stack. (the pop() method removes the element at the top of the stack. The peek() method does not modify the Stack.) Write 'peek' using only the methods that currently exist in the Stack class. ? import java.util.* public class Stack { private ArrayList<String> elements = new ArrayList<>(); public String pop() { ? if (elements.isEmpty()) { return null; } String top = elements.get(elements.size() - 1); elements.remove(elements.size() - 1); return top; } public void push(String element) { ? elements.add(element); } public boolean isEmpty() { ? return elements.isEmpty(); } }
Added by Scott F.
Close
Step 1
Step 1: We need to write a method called "peek" that returns the String at the top of the Stack without removing it. Show more…
Show all steps
Your feedback will help us improve your experience
Supreeta N and 82 other AP CS educators are ready to help you.
Ask a new question
Labs
Want to see this concept in action?
Explore this concept interactively to see how it behaves as you change inputs.
Key Concepts
Recommended Videos
In Java: Write a method called maxToTop that takes a stack of integers as a parameter and moves the largest value in the stack to the top of the stack, leaving all other values in their original order. You may assume that the stack does not contain any duplicates. For example, if a stack s stores [27, 5, 42, -11, 0, 19], the call of maxToTop(s) should change it to store [27, 5, -11, 0, 19, 42]. If the stack is empty, your method should not change it. Use one queue as auxiliary storage.
Supreeta N.
Write pseudo-code for problems requiring code. Do not write Java, Python, or C++. You are responsible for the appropriate level of detail. a) Use the operations push, pop, peek, and empty to construct an operation that sets i to the bottom element of the stack, leaving the stack unchanged. (Hint: use an auxiliary stack.) b) Use the operations push, pop, peek, and empty to construct an operation that sets i to the third element from the bottom of the stack. The stack may be left changed.
Christian O.
Recommended Textbooks
Computer Science and Information Technology
Introduction to Programming Using Python
Computer Science - An Overview
Transcript
Watch the video solution with this free unlock.
EMAIL
PASSWORD