Add a getFirst method to the C15e2 program that removes the first node on the li
ID: 3656912 • Letter: A
Question
Add a getFirst method to the C15e2 program that removes the first node on the list and returns its data. If the list is empty, getFirst throws an exception. Test your method against both null and non-null list. class C15e2 { public static void main(String[] args) { MyLinkedListL2 list = new MyLinkedListL2(); list.addFirst(1); list.addFirst(2); list.addFirst(3); System.out.println("Numbers on list"); list.traverse(); } } //============================================== class MyLinkedListL2 { private class Node { private Node link; private int x; } //---------------------------------- private Node first = null; //---------------------------------- public void addFirst(int d) { Node newNode = new Node(); newNode.x = d; newNode.link = first; first = newNode; } //---------------------------------- public void traverse() { Node p = first; while (p != null) { System.out.println(p.x); p = p.link; } } }Explanation / Answer
public int getFirst() { int value=-1; Node p = first; if (p != null) { value=p.x; p = p.link; } return value; }
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.