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

Add a length method to the myLinkedListL1 class news that returns the length of

ID: 3656886 • Letter: A

Question

Add a length method to the myLinkedListL1 class news that returns the length of the list (the number of nodes). Test your length method against both null and non-null list. class myLinkedListL1 { public static void main(String[] args) { MyLinkedListL1 list = new MyLinkedListL1(); list.addFirst(1); list.addFirst(2); list.addFirst(3); System.out.println("Numbers on list"); list.traverse(); } } //============================================== class MyLinkedListL1 { 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

package com.cramster.nov16; public class LinkedListTest { public static void main(String[] args) { LinkedList list = new LinkedList(); list.addFirst(1); list.addFirst(2); list.addFirst(3); System.out.println("Numbers on list"); list.traverse(); System.out.printf("Length : %d ",list.length()); LinkedList list1 = new LinkedList(); System.out.println("Numbers on list1"); list1.traverse(); System.out.printf("Length : %d ",list1.length()); } } package com.cramster.nov16; public class LinkedList { 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; } } public int length() { int count = 0; Node p = first; while(p!= null) { count++; p = p.link; } return count; } }

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