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; } } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.