Question: complete the implementation of the three methods shown below. The first one counts the number of occurrences of x in the list. The second removes
complete the implementation of the three methods shown below.
The first one counts the number of occurrences of x in the list.
The second removes all duplicate values. For example, if 7 occurs 3 times in the list, then 2 of the 7s will be removed. The method also returns the number of removed values.
The third method duplicates every value in a list, so that [2-4-5-7-8-z] would become [2-2-4-4-5-5-7-7-8-8-z]. Remember that the list is sorted.
// Sorted linked list with a sentinel node // Skeleton code for lab test
import java.util.Scanner;
class SortedLL { // internal data structure and // constructor code to be added here class Node { public int data; public Node next; } private Node head, z; public SortedLL () { z = new Node(); z.next = z; head = z; } // this is the crucial method public void insert(int x) { Node prev, curr, t; t = new Node(); t.data = x; z.data = x; prev = null; curr = head; while(curr.data < x) { prev = curr; curr = curr.next; } t.next = curr; if(prev == null) head = t; else prev.next = t; } public int count(int x){ int c = 0; return c; }
public int removeDuplicates() { int c = 0;
return c; }
public void duplicate(){ } public void display() { Node t = head; System.out.print(" Head -> "); while( t != z) { System.out.print(t.data + " -> "); t = t.next; } System.out.println("Z "); } public static void main(String args[]) { SortedLL list = new SortedLL(); list.display(); double x; int r, i; for(i = 1; i <= 10; ++i) { x = (Math.random()*10.0); r = (int) x; list.insert(r); } list.display(); i = 7; r = list.count(i); System.out.println("Number of " + i + "s is " + r);
r = list.removeDuplicates(); System.out.println(" Number of removals = " + r); list.display(); list.duplicate(); System.out.println(" List duplicated"); list.display();
} }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
