In: Computer Science
For a LinkedList in Java how do I
- Add a method named replace() that takes in two parameters (the data object to replaced, followed by the one to be inserted) that will remove the first occurrence of the item to be replaced and add the second parameter to the list. The method returns a boolean - true if the item to be replaced was found, false if not
- Add an instance method named showList() (no parameters or return value) that will extract all of the values from the list and display them in order, one per line, followed by another line displaying how many values are currently in the list. If the list is empty, display the message “The list is currently empty” instead
- Overload showList() with an integer parameter which represents how many items to display on each line. The method needs to newline after the last item no matter how many items were displayed (i.e. don’t leave the cursor hanging.)
//Linked list class
class LinkedList
{
//Node class
static class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
Node head; //Head of list
//Start with the empty list
static LinkedList llist = new LinkedList();
//Inserts a new node at the front of the list
public void push(int new_data)
{
//Allocate new node and putting data
Node new_node = new Node(new_data);
//Make next of new node as head
new_node.next = head;
//Move the head to point to new Node
head = new_node;
}
//Checks whether the value x is present in linked list and
// replaces it with y
public boolean replace( int x, int y)
{
Node current = llist.head; //Initialize current
while (current != null)
{
if (current.data == x){
current.data = y ;
return true; //data found
}
current = current.next;
}
return false; //data not found
}
public void showList()
{
Node n = llist.head;
while (n != null) {
System.out.println(n.data);
n = n.next;
}
}
public void showList(int N)
{
int i = 1;
Node n = llist.head;
while (n != null) {
System.out.print(n.data + " ");
n = n.next;
if (i == N){
i = 0;
System.out.println();
}
++i;
}
System.out.println("\n");
}
//Driver function to test the above functions
public static void main(String args[])
{
/*Use push() to construct below list
14->21->11->30->10 */
llist.push(10);
llist.push(10);
llist.push(11);
llist.push(21);
llist.push(14);
llist.push(19);
llist.push(39);
llist.push(18);
llist.push(25);
llist.push(1);
llist.showList();
if (llist.replace( 10, 31))
System.out.println("\nYes\n");
else
System.out.println("\nNo\n");
llist.showList();
llist.showList(3);
}
}
Screen shot :