Assume that the everything below is part of an existing Java class. Please help
ID: 3602592 • Letter: A
Question
Assume that the everything below is part of an existing Java class. Please help me complete the arrayInsert method below in Java. The method parameters must NOT be altered.
static class Node {
public Node (double item, Node next) { this.item = item; this.next = next; }
public double item;
public Node next;
}
int N; // number of nodes in list
Node first; // reference to the first node in the list
// arrayInsert
//
// insert the value in the array at position k
// positions are numbered starting with 0
// elements k through N-2 are moved 'up' one position to make a space for the new value
// i.e. element k moves to position k+1
// the initial value in position N-1 is not preserved
// preconditions: 0 <= k <= N-1
//
public static void arrayInsert( double[] arr, double value, int k) {
// To do 4. Complete this method
}
The test cases look like this…
private static void runArrayTests () {
testArrayInsert (99, 1, "11", "11 99");
testArrayInsert (99, 0, "11 21 31 41 51", "99 11 21 31 41 51");
testArrayInsert (99, 1, "11 21 31 41 51", "11 99 21 31 41 51");
testArrayInsert (99, 2, "11 21 31 41 51", "11 21 99 31 41 51");
testArrayInsert (99, 3, "11 21 31 41 51", "11 21 31 99 41 51");
testArrayInsert (99, 4, "11 21 31 41 51", "11 21 31 41 99 51");
testArrayInsert (99, 5, "11 21 31 41 51", "11 21 31 41 51 99”);
StdOut.println ("Finished array tests");
}
Thank you for your help!!
Explanation / Answer
Hello, here is the code for the method arrayInsert(). Inthis method I have used the concept of singly linked list to insert the node at the specific position. If the list is empty then the new node is added to list and it is returned. If we want to insert at position 0 then put the entire list one position forward and put new node at the begining , o.w. to the specific position provided. Please give me feedback to this solution. Thank you
public static void arrayInsert( double[] arr, double value, int k)
{
Node p=first;
N=arr.length;
for(i=0 ; i<= N-1 ; i++)
{
new Node(arr[i] , p);
p=p->next;
}
Node Head=first;
Node newNode = new Node();
Node newNode.item = value;
//Empty List - Returned newly created node or null
if (first==null)
{
return NewNode;
}
//Inserting a Node ahead of the List
if (k == 0)
{
NewNode.next = first;
return NewNode;
}
int pos = 0;
while (pos < k -1 && first.next != null)
{
first = first.next;
pos++;
}
//Inserting a Node in-between a List or at the end of of a List
Node p= first.next;
first.next = NewNode;
first = first.next;
first.next = p;
return Head;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.