Question

In: Computer Science

Improve class OurLinkedList, so that its users can readily access a list's middle node. Readily here...

Improve class OurLinkedList, so that its users can readily access a list's middle node. Readily here means that when users instantiate an OurLinkedList object, they can access the node in the middle of the list without starting from the head, counting how many nodes to the end, then going back to the head, and skipping half as many nodes forward. In fact, there should be no counting for this improvement. Notice that lists with an even number of nodes, do not have a well defined middle node and it is up to you to determine which node near the middle will be considered the middle one.

Your improvement must be delivered only in the form of a new class that extends OurLinkedList. Name the extending class, after yourself, as following:

class YourfirstnameLinkedList extends OurLinkedList { ... }

replacing Yourfirstname above, with your actual first name (e.g., MyLinkedList).

SOURCE CODE FOR QUESTION

public class OurLinkedList {


class Node {
  
String value;
Node next;
  
Node(String v) {
value = v;
next = null;
} // constructor Node
} // class Node

/**
* Accessor for the field size.
* @return number of nodes in the list.
*/
public int getSize() {
return size;
} // method getSize

  
public boolean nodeExists(String v) {
// Initial assumption: no node found with string v
boolean stringFound = false;
// Start from the beginning.
Node currentNode = head;
if ( currentNode == null) {
// Empty list.
stringFound = false;
} else {
// List is not empty. Let's check if the last node contains
// string we are looking for. We do this here, because the
// last node is unreachable in a loop that terminates when
// .next == null.
stringFound = tail.value == v;
// Search through the rest of the linked list, hopping from
// node to node, following the .next pointer.
while (currentNode.next != null) {
if ( currentNode.value == v) {
stringFound = true;
}
currentNode = currentNode.next;
}
}
return stringFound;
} // method nodeExists


public void addNode(String v) {
if (!nodeExists(v)) {
// The list does not contain a node with the given string.
// Let's create one and call it newNode.
Node newNode = new Node(v);
// We are adding this newNode to the list, so let's increase the size.
size++;
// Now we need to determine where to add this new node.
if (head == null) {
// List is empty. Make this newNode the list's head.
head = new Node(v);
// Because the list is empty, make this node its tail as well.
tail = head;
} else {
// The list is not empty. Find its tail node and add the
// newNode after it.
tail.next = newNode;
// Make the newNode, the list's new tail.
tail = newNode;
}
}
}

public boolean remove(String v) {
boolean success = false;
if (nodeExists(v)) {
success = true;
}
return success;
}

class MyLinkedList extends OurLinked {...}


public static void main(String[] args) {
OurLinkedList demo = new OurLinkedList();
}

}

The question wants us to find the middle of the list immediately without traversing the linked list conventionally but any help is great. There is no need to print the list just to know where the middle of the list is.

Solutions

Expert Solution

  1. The improved code in MyLinkedList class uses the single pointer mid which moves forward only when the counter variable is odd.
  2. This ensures mid moves half the nodes only from the entire list.
  3. There is no getting the size and traversing the list until size/2 elements.
  4. Proper null checks are done to avoid null pointer exception.

public class OurLinkedList {


class Node {

String value;
Node next;

Node(String v) {
value = v;
next = null;
} // constructor Node
} // class Node

/**
* Accessor for the field size.
* @return number of nodes in the list.
*/
public int getSize() {
return size;
} // method getSize


public boolean nodeExists(String v) {
// Initial assumption: no node found with string v
boolean stringFound = false;
// Start from the beginning.
Node currentNode = head;
if (currentNode == null) {
// Empty list.
stringFound = false;
} else {
// List is not empty. Let's check if the last node contains
// string we are looking for. We do this here, because the
// last node is unreachable in a loop that terminates when
// .next == null.
stringFound = tail.value == v;
// Search through the rest of the linked list, hopping from
// node to node, following the .next pointer.
while (currentNode.next != null) {
if (currentNode.value == v) {
stringFound = true;
}
currentNode = currentNode.next;
}
}
return stringFound;
} // method nodeExists


public void addNode(String v) {
if (!nodeExists(v)) {
// The list does not contain a node with the given string.
// Let's create one and call it newNode.
Node newNode = new Node(v);
// We are adding this newNode to the list, so let's increase the size.
size++;
// Now we need to determine where to add this new node.
if (head == null) {
// List is empty. Make this newNode the list's head.
head = new Node(v);
// Because the list is empty, make this node its tail as well.
tail = head;
} else {
// The list is not empty. Find its tail node and add the
// newNode after it.
tail.next = newNode;
// Make the newNode, the list's new tail.
tail = newNode;
}
}
}

public boolean remove(String v) {
boolean success = false;
if (nodeExists(v)) {
success = true;
}
return success;
}
  
   //My code here
  
   class MyLinkedList extends OurLinked {
       public Node middleElement(Node node){
           //if empty list is provided then return null and not proceed with any of the computation
           //Here we are using the concept to find the middle element only when c is odd
           // So that mid moves only half the distance automatically without actually calculating the length of the list
           if(node!=null){
               Node mid= node;
               int c=0;
               while(node!=null){
                   if(c%2!=0) // mid moves only when the counter is odd , ensuring it moves the half of current list
                       mid=mid.next;
                   ++c;
                   node=node.next;
               }
           return mid;
           }
           //return node only if it is empty list and the null check is done in the driver method
           return node;
       }
   }

   @driver method
   public static void main(String[] args) {
       OurLinkedList demo = new OurLinkedList();
       Node mid= demo.middleElement(head);
       if(mid!=null)
           System.out.println(mid.data);
      
   }

}


Related Solutions

​​​​​​This is an assignment that I'm having trouble figuring out in python: Modify Node class so...
​​​​​​This is an assignment that I'm having trouble figuring out in python: Modify Node class so it has a field called frequency and initialize it as one. Add a search function. If a number is in the list, return its frequency. Modify Insert function. Remove push, append, and insertAfter as one function called insert(self, data). If you insert a data that is already in the list, simply increase this node’s frequency. If the number is not in the list, add...
Implement a class called DoublyLinkedList. In the main function, instantiate the DoublyLinkedList class and make sure that there is a user loop and a menu so that the user can access all the list operators.
C++  Implement a class called DoublyLinkedList. In the main function, instantiate the DoublyLinkedList class and make sure that there is a user loop and a menu so that the user can access all the list operators. You should implement the following operators, and any others that you may deem best. DestroyList InitializeList GetFirst InsertFirst, InsertLast, Insert DeleteFirst, DeleteLast, Delete IsEmpty Length Print, ReversePrint
Is it possible to reduce the cost of healthcare so that everyone can have access to...
Is it possible to reduce the cost of healthcare so that everyone can have access to affordable healthcare services? Do you feel that the Patient Protection and Affordable Care Act is a good step toward reducing healthcare costs in our nation? Why or why not?
here are several access control models and in class we learnt specifically about 3 flavors: Mandatory...
here are several access control models and in class we learnt specifically about 3 flavors: Mandatory Access Control (MAC), Role Based Access Control (RBAC), and Discretionary Access Control (DAC). In your own words differentiate these 3 models. Your answer should include a specific example where a specific model is best.
How can students improve listening during the class? Identify how you can specifically improve your personal...
How can students improve listening during the class? Identify how you can specifically improve your personal and professional listening skills this week in this course, at home, and at work. Are you carefully reading others posts, course syllabus and rubric? Do you give your full attention to family members or coworkers? Minimum 100 words
How can we improve the access to oral health care for vulnerable and underserved population?
How can we improve the access to oral health care for vulnerable and underserved population?
How can an advanced nurse or APRN improve access and health outcomes for marginalized populations and...
How can an advanced nurse or APRN improve access and health outcomes for marginalized populations and communities? What individual knowledge, skills , and attitudes are necessary to improve health inequities?
How can measurement be used to improve daily operations here at college ? Think of just...
How can measurement be used to improve daily operations here at college ? Think of just one example and explain. 400 word max
Item 1: Entity A purchased land adjacent to its plant to improve access for trucks making...
Item 1: Entity A purchased land adjacent to its plant to improve access for trucks making deliveries. Expenditures incurred in purchasing the land were as follows: Purchase price $55,000 Broker’s fees 6,000 Title search and other fees 5,000 Demolition of an old building on the property, 5,700 Grading 1,200 Digging foundation for the road 3,000 Laying and paving driveway 25,000 Lighting 7,500 Signs 1,500. List the items and amounts that should be included in the Land account. Item 2: Equipment...
How to validate Javascript form data? Here is the code. Can someone modify it so that...
How to validate Javascript form data? Here is the code. Can someone modify it so that all the information is validated? Thanks. <!DOCTYPE html> <html lang="en"> <head>    <title>Music Survey</title>    <meta charset="utf-8"> </head> <style>    legend { font-weight:bold;    }    </style> <body> <h1>Music Survey</h1> <form method="post" action=""> <label for="myname"><b>Name:</b></label>        <input type="text" name="myname" id="myname">        <br><br> <label for="myemail"><b>Email:</b></label>        <input type="email" name="myemail" id="myemail">        <br><br>   <fieldset> <legend>Select Your Favorite Types of Music:</legend> <input type="checkbox"...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT