Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A stack lets you peek at the top entry without removing it. For some application

ID: 3709967 • Letter: A

Question

A stack lets you peek at the top entry without removing it. For some applications, you might also want to peek at the entry beneath the top entry without removing it.

Write two peek2 methods, one for LinkedStack and one for ArrayStack. Submit only the two peek2 methods (not the full classes).

Here is the method header for both classes:

public T peek2()

If the stack has two entries or more, peek2 returns the second entry from the top without altering the stack.

If the stack has fewer than two entries, peek2 should either return null or throw an exception. You can decide, but be consistent with the peek method and choose an action that makes the most logical sense!

Explanation / Answer

public class LinkedStack { static class Node { private T data; private Node next; } private Node head; public void display() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } public T pop2() { if(head == null || head.next == null) { return null; } else { return (T) head.next.data; } } } public class ArrayStack { private T[] data; private int top; public void display() { for(int i = 0; i = 1) { return data[top-1]; } else { return null; } } }
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote