/* * Complete the methods below. * All of these methods modify the list. * Use t
ID: 3788245 • Letter: #
Question
/*
* Complete the methods below.
* All of these methods modify the list.
* Use the function checkInvariants to ensure that your list is well-formed after you modify it.
* Note that this list keeps track of the number of elements N.
* It is important that N accurately reflect the length of the list.
*
* You may not add any fields to the node or list classes.
* You may not add any methods to the node class.
*
* You MAY add private methods to the list class (helper functions for the recursion).
*/
public class MyLinked2 {
static class Node {
public Node (double item, Node next) { this.item = item; this.next = next; }
public double item;
public Node next;
}
int N;
Node first;
// delete the kth element (where k is between 0 and N-1 inclusive)
public void delete (int k) {
if (k < 0 || k >= N) throw new IllegalArgumentException ();
// TODO
}
// reverse the list "in place"... without creating any new nodes
public void reverse () {
// TODO
}
// remove all occurrences of item from the list
public void remove (double item) {
// TODO
}
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
public class MyLinked2 {
static class Node {
public Node (double item, Node next) {
this.item = item;
this.next = next;
}
public double item;
public Node next;
}
int N;
Node first;
// delete the kth element (where k is between 0 and N-1 inclusive)
public void delete (int k) {
if (k < 0 || k >= N) throw new IllegalArgumentException ();
Node temp = first;
// moving temp to (k-1)th node
for(int i=1; i<k-1; i++){
temp = temp.next;
}
// now temp points to (k-1)th node
// deleting kth node
temp.next = temp.next.next;
N = N-1; // decreasing N value
}
// reverse the list "in place"... without creating any new nodes
public void reverse () {
Node prev = null;
Node current = first;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
first = prev;
}
// remove all occurrences of item from the list
public void remove (double item) {
if(N == 0)
return;
// removing all nodes having value = item from head and moving head
while(first != null && first.item == item){
first = first.next;
N = N-1;
}
Node temp = first;
// removing all others nodes having item = item
while(temp.next != null){
if(temp.next.item == item){
temp.next = temp.next.next;
N= N-1;
}else{
temp = temp.next;
}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.