Linked Lists a. Complete the recursive printRec method of the following incomple
ID: 3594906 • Letter: L
Question
Linked Lists
a. Complete the recursive printRec method of the following incomplete singly-linked list implementation.
b. Complete the method get(int index) that returns the data item at index. Assume that the list is zero-indexed. Throw appropriate exceptions.
-------------------------------------------------------------------------------------
class Node {
public int data;
public Node next;
public Node(int d, Node n) {
data = d;
next = n;
}
}
public class LinkedList {
private Node front;
public LinkedList() {
front = null;
}
public void printList() {
// calls the recursive print method
// to print each data item of the list.
printRec(front);
}
private void printRec(Node front){
// to be completed as a recursive method
// prints the data items of the list,
// separated by a comma.
public int get(int index){
// to be completed
// gets the item at index.
// throws appropriate exceptions when the index is invalid
// or when the list is empty
}
Explanation / Answer
Here is the update for you:
class Node
{
public int data;
public Node next;
public Node(int d, Node n)
{
data = d;
next = n;
}
}
public class LinkedList1
{
private Node front;
public LinkedList1()
{
front = null;
}
public void printList()
{
// calls the recursive print method
// to print each data item of the list.
printRec(front);
}
private void printRec(Node front)
{
// to be completed as a recursive method
// prints the data items of the list,
// separated by a comma.
if(front != null)
{
System.out.print(front.data + " ");
printRec(front.next);
}
}
public int get(int index)
{
// to be completed
// gets the item at index.
// throws appropriate exceptions when the index is invalid
// or when the list is empty
Node temp = front;
for(int i = 0; i < index && temp != null; i++)
temp = temp.next;
return temp.data;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.