Create a linked list of names using a class called NameNode. The NameNode class
ID: 673476 • Letter: C
Question
Create a linked list of names using a class called NameNode. The NameNode class should have in it a string that stores the last name of an individual, and a link to another NameNode. This class should also contain the following: // constructor (passed a last name, and next node to point to or null) // getters for name and next node // setter for next node Develop a main method that contains code for testing the linked list. 2. Create a NameList class that stores a linked list of names, containing the following constructor and methods: // a no-arg constructor (to create an empty list) // isEmpty method (which returns true if the list is empty) // append method (to append a new name to the list) // print method(that displays the complete list of name, one name per line) Write a simple main program for testing your class. For this lab, turn in each of the Java files created.
Explanation / Answer
Comments and output attached
public class NameList
{
//head node referrence
private Node head;
private int listCount;
// constructor
public NameList ()
{
head = new Node(null);
listCount = 0;
}
public void add(String lastName)
{
Node node = new Node(lastName);
Node current = head;
while(current.getNext() != null)
{
current = current.getNext();
}
current.setNext(node);
listCount++;// increment the number of elements variable
}
public void add(String lastName, int index)
{
Node node = new Node(lastName);
Node current = head;
for(int i = 1; i < index && current.getNext() != null; i++)
{
current = current.getNext();
}
node.setNext(current.getNext());
// setting next referrence
current.setNext(node);
listCount++;// nodes size incrementing
}
//isEmpty method
public boolean isEmpty()
{
if(listCount > 0){
return false;
}
return true;
}
//tostring method
public String toString()
{
NameNode current = head.getNext();
String res = "";
while(current != null)
{
res += "(" + current.getData().toString() + ")";
current = current.getNext();
}
return res;
}
private class NameNode
{
// variables declared
NameNode next;
String lastName;
// headnode constructor
public NameNode(String lastName)
{
next = null;
lastName = lastName;
}
//parameterised constructor
public NameNode(String lastName, NameNode _next)
{
next = _next;
lastName = lastName;
}
//getter setter methods
public NameNode getNext()
{
return next;
}
public void setNext(NameNode _next)
{
next = _next;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.