Question

In: Computer Science

//package Lab7_2_LinkedList_Sol; public class Runner { public static void main(String[] args){ MyLinkedList ll = new MyLinkedList(10.1);...

//package Lab7_2_LinkedList_Sol;

public class Runner {
  public static void main(String[] args){    
    MyLinkedList ll = new MyLinkedList(10.1);    
    ll.append(10.5);
    ll.append(8.11);    
    ll.append(15.6);  
    System.out.println("--------Printing via print method------------");        
    ll.print();    
    
    System.out.println("--------Printing via initiator------------");    
    ll.initiateIterator();
    Object o = null;
    while ( (o=ll.nextObject())!=null){      
      System.out.println((Double)(o));
    }    

    ll.initiateIterator();
    Object largest=ll.nextObject();
    while (((o=ll.nextObject())!=null)){
      if ((Double)o>(Double)largest)
        largest=o;
    }
    System.out.println("The largest number in the LL is: "+largest);
    
    System.out.println("--------Number insertion------------");
    ll.insert(100.2145, 4);
    ll.insert(110.2145, 0);    
    ll.insert(120.2145, 2);
    ll.insert(180.2145, 8);    
    ll.print();
    
    System.out.println("--------Removal------------");
    int ind=3;
    System.out.println("Removal of pos "+ind+" is: "+ll.remove(ind));
    ll.print();
    ind=5;
    System.out.println("Removal of pos "+ind+" is: "+ll.remove(ind));
    ll.print();    
    ind=5;
    System.out.println("Removal of pos "+ind+" is: "+ll.remove(ind));
    ll.print();        

    ind=0;
    System.out.println("Removal of pos "+ind+" is: "+ll.remove(ind));
    ll.print();        
    
    System.out.println("--------Creating Box linked list------------");    
    
    MyLinkedList lb = new MyLinkedList();    
    lb.append( new Rectangle(10.1, 20.2) );
    lb.append( new Rectangle(5.3, 15.4) );    
    lb.append( new Rectangle(2.3, 4.4) );    
    lb.append( new Rectangle(50.3, 20.4) );   
    System.out.println("--------Printing Box linked list------------");        
    lb.print();
    
    ind=4;
    System.out.println("Insertion of pos "+ind+" is "+
              lb.insert(new Rectangle(100.1, 200.2), ind));
 
    ind=3;
    System.out.println("Insertion of pos "+ind+" is "+
              lb.insert(new Rectangle(102.1, 204.2), ind));    
    
    ind=7;
    System.out.println("Insertion of pos "+ind+" is "+
              lb.insert(new Rectangle(502.1, 504.2), ind));    
    System.out.println("--------Printing Box linked list------------");        
    
    lb.print();    
    
    ind=4;
    System.out.println("Removal of pos "+ind+" is: "+lb.remove(ind));

    System.out.println("--------Printing Box linked list------------");            
    lb.print();       
    
    System.out.println("----------Largest rectangle------");
    // Iterate, find, and report the largest 
    // Rectangle from lb
    lb.initiateIterator();
    Rectangle largestRect = (Rectangle) lb.nextObject();
    while ((o=lb.nextObject())!=null){
      Rectangle r = (Rectangle) o;
      if (r.getArea()> largestRect.getArea())
        largestRect=r;
    }
    System.out.println("Largest rectangle: ");
    System.out.println(largestRect.toString());
    
  }
}

------------------------------------------------------------------------------------------------

//package Lab7_2_LinkedList_Sol;

public class Rectangle {
  double length, width;
  Rectangle(){}
  Rectangle(double l, double w){
    length=l;
    width=w;
  }
  @Override
  public String toString(){
    return "Length="+length+" Width="+width;
  }
  
  double getArea(){
    return length*width;
  }  
}

----------------------------------------------------------------------------------

//package Lab7_2_LinkedList_Sol;

public class Node {
  Object data;  
  Node next;

  Node(){}
  Node(Object obj){
    data = obj;
  } 
  @Override
  public String toString(){
    return data.toString();
  }
}

---------------------------------------------------------------------

//package Lab7_2_LinkedList_Sol;

public class MyLinkedList {
  Node head;
  Node iterator;
  MyLinkedList(){}
  
  MyLinkedList(Object obj){
    head = new Node(obj);
  }
  
  void initiateIterator(){
    iterator=head;
  }
  
  Object nextObject(){
    if (iterator==null)
      return null;
    Object returnee = iterator.data;
    iterator = iterator.next;
    return returnee;
  }
  
  void append(Object obj){
    if (head==null){
      head = new Node(obj);
      return;
    }
    Node temp = head;
    while (temp.next!=null){      
      temp=temp.next;
    }
    temp.next= new Node(obj);    
  }
  
  /**
   * Your solution here
   * Remove a node in position pos of the linked list.
   * Positions start from zero.
   * @param pos
   * @return True if removal is successful.
   * Otherwise, return false.
   */
  boolean remove(int pos){
  
  }
  
  /**
   * Your solution here
   * Insert the object insertee in a Node at position pos.
   * Positions start from zero.
   * @param insertee
   * @param pos
   * @return True if removal is successful.
   * Otherwise, return false.
   */
  boolean insert(Object insertee, int pos){
    
  }
  
  void print(){
    Node temp = head;    
    while (temp!=null){
      System.out.println(temp);
      temp=temp.next;
    }    
  }
  
}

From the given above java files write a java code for MyLinkedList.java to remove a node in position pos of the linked list,  return True if removal is successful. Otherwise, return false. And also insert the object insertee in a Node at position pos. Return True if removal is successful. Otherwise, return false. In the given space write the java code . Just change the MyLinkedList.java file.

Solutions

Expert Solution

I have implemented below two methods for MyLinkedList class ::

1> boolean insert(Object insertee, int pos) :-

Note: The position of first node in the MyLinkedList is start from 0.

This method insert the node at the given position in below three cases::

1> if the pos = 0 then insert node at the first position and method will return true.

2> if the pos = total Node +1 then insert new node at the last position method will return true.

3> if the pos is between the first and last node then insert new node to the given position method will return true.

If the position is greater then total node of the MYLinkedList then method will return false.

2> boolean remove(int pos) :-

Note: The position of first node in the MyLinkedList is start from 0.

This method remove the node from the given position in below two cases::

1> if the pos = 0 then remove the first node and method will return true.

2> if the pos = last Node then remove last node and method will return true.

3> if the pos is between the first and last node then remove node from the given position and method will return true.

If the position is greater then total node of the MYLinkedList then method will return false.

MyLinkedList class with above two methods that are highlighted in the code :-

class MyLinkedList {
Node head;
Node iterator;
MyLinkedList(){}
  
MyLinkedList(Object obj){
head = new Node(obj);
}
  
void initiateIterator(){
iterator=head;
}
  
Object nextObject(){
if (iterator==null)
return null;
Object returnee = iterator.data;
iterator = iterator.next;
return returnee;
}
  
void append(Object obj){
if (head==null){
head = new Node(obj);
return;
}
Node temp = head;
while (temp.next!=null){
temp=temp.next;
}
temp.next= new Node(obj);
}
  
/**
* Your solution here
* Remove a node in position pos of the linked list.
* Positions start from zero.
* @param pos
* @return True if removal is successful.
* Otherwise, return false.
*/
boolean remove(int pos){
  
// if list is empty then return false
if(head == null)
return false;
  
/*
first check whether pos is greater then length of the list or not?
IF GREATER THAN THEN RETURN FALSE
OTHERWISE REMOVE NODE FROM THE GIVEN POS
*/
int count = 0;
  
// store head of lsit
Node curr = head;
  
// store prev for delte curr node from the list
Node prev = curr;
// run the loop untill the list not become empty
while(curr != null){
  
// if we get position then remove the node of that position
if(count == pos){
  
/*
case 1: If the pos == 1 then make head
next of removable node
*/
if(pos == 0){
  
// make head next of curr node
head = curr.next;
return true;
}
  
  
/*
case 2: if position is point to the last node of the list

*/
// if next of curr is null then removable node is last node
else if(curr.next == null){
  
// store null to the next of prev node of removable node
prev.next = null;
return true;
}
  
/*
case 3: position is between the first and last node
*/
// store the next of removable node to the prev of removable node
else{

prev.next = curr.next;
return true;
}
}
  
// increment the counter
count++;
  
// track prev node
prev = curr;
  
// goto the next node
curr = curr.next;
}
// otherwise return false (there is no node at the given position)
return false;
}
  
/**
* Your solution here
* Insert the object insertee in a Node at position pos.
* Positions start from zero.
* @param insertee
* @param pos
* @return True if removal is successful.
* Otherwise, return false.
*/
boolean insert(Object insertee, int pos){
  
// create new node which will be inserted to the linkedlist
Node newNode = new Node(insertee);
  
/*
case 1: if the list is empty then insert to the first
*/
if(head == null){
  
// make new node as a front
head = newNode;
  
// return true node is inserted at the first position
return true;
}
  
  
/*
case 2: if position is 1 then add the newNode to the first
*/
if(pos == 0){
  
// first store the first nod eto the next of newNode
newNode.next = head;

// make new node as a front
head = newNode;
  
// node is inserted at the first position
return true;

}
  
  
  
int count = 0;
  
// store head
Node curr = head;
  
// track prev for insrtion of newNode
Node prev = head;
  
// run the loop untill the list is not empty
while(curr != null){

// if pos is less then count
if(count <= pos){
  
// count is equal to pos then insert the node
if(count == pos){

// store the curr into the next of newNode
newNode.next = curr;
  
// then store newNode to the next of prev
prev.next = newNode;
  

// then return true
return true;
}
}
  
// increment the count
count++;
  
// store prev of curr
prev = curr;
  
// goto the next node
curr = curr.next;
}   
  
// newNode inserted as a last node
if(prev.next == null && count == pos){

// store newNode to the prev of next
prev.next = newNode;

// then set null to the lst node
newNode.next = null;
return true;

}
  
return false;
}

  
void print(){
Node temp = head;
while (temp!=null){
System.out.println(temp);
temp=temp.next;
}
}
  
}

Here, I have attached the Runner.java will demonstrate the functionality of MyLinkedList class.

Program:-

public class Runner {
  public static void main(String[] args){    
    MyLinkedList ll = new MyLinkedList(10.1);    
    ll.append(10.5);
    ll.append(8.11);    
    ll.append(15.6);  
    System.out.println("--------Printing via print method------------");        
    ll.print();    
    
    System.out.println("--------Printing via initiator------------");    
    ll.initiateIterator();
    Object o = null;
    while ( (o=ll.nextObject())!=null){      
      System.out.println((Double)(o));
    }    

    ll.initiateIterator();
    Object largest=ll.nextObject();
    while (((o=ll.nextObject())!=null)){
      if ((Double)o>(Double)largest)
        largest=o;
    }
    System.out.println("The largest number in the LL is: "+largest);
    
    System.out.println("--------Number insertion------------");
    
    ll.insert(100.2145, 4);
    ll.insert(110.2145, 0);    
    ll.insert(120.2145, 2);
    ll.insert(180.2145, 8);    
    ll.print();
    
    System.out.println("--------Removal------------");
    int ind=3;
    System.out.println("Removal of pos "+ind+" is: "+ll.remove(ind));
    ll.print();
    ind=5;
    System.out.println("Removal of pos "+ind+" is: "+ll.remove(ind));
    ll.print();    
    ind=5;
    System.out.println("Removal of pos "+ind+" is: "+ll.remove(ind));
    ll.print();        

    ind=0;
    System.out.println("Removal of pos "+ind+" is: "+ll.remove(ind));
    ll.print();        
    
    System.out.println("--------Creating Box linked list------------");    
    
    MyLinkedList lb = new MyLinkedList();    
    lb.append( new Rectangle(10.1, 20.2) );
    lb.append( new Rectangle(5.3, 15.4) );    
    lb.append( new Rectangle(2.3, 4.4) );    
    lb.append( new Rectangle(50.3, 20.4) );   
    System.out.println("--------Printing Box linked list------------");        
    lb.print();
    
    ind=4;
    System.out.println("Insertion of pos "+ind+" is "+
              lb.insert(new Rectangle(100.1, 200.2), ind));
 
    ind=3;
    System.out.println("Insertion of pos "+ind+" is "+
              lb.insert(new Rectangle(102.1, 204.2), ind));    
    
    ind=7;
    System.out.println("Insertion of pos "+ind+" is "+
              lb.insert(new Rectangle(502.1, 504.2), ind));    
    System.out.println("--------Printing Box linked list------------");        
    
    lb.print();    
    
    ind=4;
    System.out.println("Removal of pos "+ind+" is: "+lb.remove(ind));

    System.out.println("--------Printing Box linked list------------");            
    lb.print();       
    
    System.out.println("----------Largest rectangle------");
    // Iterate, find, and report the largest 
    // Rectangle from lb
    lb.initiateIterator();
    Rectangle largestRect = (Rectangle) lb.nextObject();
    while ((o=lb.nextObject())!=null){
      Rectangle r = (Rectangle) o;
      if (r.getArea()> largestRect.getArea())
        largestRect=r;
    }
    System.out.println("Largest rectangle: ");
    System.out.println(largestRect.toString());
    
  }
}
//------------------------------------------------------------------------------------------------

//package Lab7_2_LinkedList_Sol;

class Rectangle {
  double length, width;
  Rectangle(){}
  Rectangle(double l, double w){
    length=l;
    width=w;
  }
  @Override
  public String toString(){
    return "Length="+length+" Width="+width;
  }
  
  double getArea(){
    return length*width;
  }  
}
//----------------------------------------------------------------------------------

//package Lab7_2_LinkedList_Sol;

class Node {
  Object data;  
  Node next;

  Node(){}
  Node(Object obj){
    data = obj;
  } 
  @Override
  public String toString(){
    return data.toString();
  }
}
//---------------------------------------------------------------------

//package Lab7_2_LinkedList_Sol;

class MyLinkedList {
  Node head;
  Node iterator;
  MyLinkedList(){}
  
  MyLinkedList(Object obj){
    head = new Node(obj);
  }
  
  void initiateIterator(){
    iterator=head;
  }
  
  Object nextObject(){
    if (iterator==null)
      return null;
    Object returnee = iterator.data;
    iterator = iterator.next;
    return returnee;
  }
  
  void append(Object obj){
    if (head==null){
      head = new Node(obj);
      return;
    }
    Node temp = head;
    while (temp.next!=null){      
      temp=temp.next;
    }
    temp.next= new Node(obj);    
  }
  
  /**
   * Your solution here
   * Remove a node in position pos of the linked list.
   * Positions start from zero.
   * @param pos
   * @return True if removal is successful.
   * Otherwise, return false.
   */
  boolean remove(int pos){
      
    // if list is empty then return false
    if(head == null)
        return false;
    
    /*
        first check whether pos is greater then length of the list or not?
        IF GREATER THAN THEN RETURN FALSE
        OTHERWISE REMOVE NODE FROM THE GIVEN POS
    */
    int count = 0;
    
    // store head of lsit
    Node curr = head;
    
    // store prev for delte curr node from the list
    Node prev = curr;
    // run the loop untill the list not become empty
    while(curr != null){
    
        // if we get position then remove the node of that position
        if(count == pos){
            
            /*
                case 1: If the pos == 1 then make head
                        next of removable node
            */
            if(pos == 0){
                
                // make head next of curr node
                head = curr.next;
                return true;
            }
            
            
            /*
            case 2: if position is point to the last node of the list
                   
            */
            // if next of curr is null then removable node is last node
            else if(curr.next == null){
                
                // store null to the next of prev node of removable node
                prev.next = null;
                return true;
            }
            
            /*
            case 3: position is between the first and last node
            */
            // store the next of removable node to the prev of removable node
            else{
               
                prev.next = curr.next;
                return true;
            }
        }
            
        // increment the counter
        count++;
        
        // track prev node
        prev = curr;
        
        // goto the next node
        curr = curr.next;
    }
    // otherwise return false (there is no node at the given position)
    return false;
  }
  
  /**
   * Your solution here
   * Insert the object insertee in a Node at position pos.
   * Positions start from zero.
   * @param insertee
   * @param pos
   * @return True if removal is successful.
   * Otherwise, return false.
   */
  boolean insert(Object insertee, int pos){
    
    // create new node which will be inserted to the linkedlist
    Node newNode = new Node(insertee);
          
    /*
        case 1: if the list is empty then insert to the first
    */
    if(head == null){
            
        // make new node as a front
        head = newNode;
        
        // return true node is inserted at the first position
        return true;
    }
        
    
    /*
        case 2: if position is 1 then add the newNode to the first
    */
    if(pos == 0){
            
        // first store the first nod eto the next of newNode
        newNode.next = head;

        // make new node as a front
        head = newNode;
        
        // node is inserted at the first position
        return true;

    }
            
        
    
    int count = 0;
    
    // store head
    Node curr = head;
    
    // track prev for insrtion of newNode
    Node prev = head;
    
    // run the loop untill the list is not empty
    while(curr != null){
       
        // if pos is less then count
        if(count <= pos){
            
            // count is equal to pos then insert the node
            if(count == pos){
                               
                // store the curr into the next of newNode
                newNode.next = curr;
                
                // then store newNode to the next of prev
                prev.next = newNode;
                
               
                // then return true
                return true;
            }
        }
        
        // increment the count
        count++;
        
        // store prev of curr
        prev = curr;
        
        // goto the next node
        curr = curr.next;
    }   
      
    // newNode inserted as a last node
    if(prev.next == null && count == pos){

        // store newNode to the prev of next
        prev.next = newNode;

        // then set null to the lst node
        newNode.next = null;
        return true;

    }
      
    return false;
  }
  
  void print(){
    Node temp = head;    
    while (temp!=null){
      System.out.println(temp);
      temp=temp.next;
    }    
  }
  
}

Output:-

I hope you will understand the above two methods.

Do you feel needful and useful then please upvote me.

Thank you.


Related Solutions

public class Runner{ public static void main(String[] args){           MylinkedList ll = new MylinkedList(10.1);...
public class Runner{ public static void main(String[] args){           MylinkedList ll = new MylinkedList(10.1);        ll.append(15.6);        ll.append(10.5);        ll.append(8.11);        ll.print();               ll.initiateIterator();        Object o = null;        while ( (o=ll.nextObject())!=null){            System.out.println((Double)(o)+100.1);        } Your solution here    // Iterate, find, and report the largest number               MylinkedList lb = new MylinkedList();        lb.append( new Rectangle(10.1, 20.2) );   ...
public class OOPExercises {     public static void main(String[] args) {         A objA = new...
public class OOPExercises {     public static void main(String[] args) {         A objA = new A();         B objB = new B();         System.out.println("in main(): ");         System.out.println("objA.a = "+objA.getA());         System.out.println("objB.b = "+objB.getB());         objA.setA (222);         objB.setB (333.33);       System.out.println("objA.a = "+objA.getA());         System.out.println("objB.b = "+objB.getB());     } } Output: public class A {     int a = 100;     public A() {         System.out.println("in the constructor of class A: ");         System.out.println("a = "+a);         a =...
package datastructure; public class UseQueue { public static void main(String[] args) { /* * Demonstrate how...
package datastructure; public class UseQueue { public static void main(String[] args) { /* * Demonstrate how to use Queue that includes add,peek,remove,pool elements. * Use For Each loop and while loop with Iterator to retrieve data. * */ } }
package datastructure; public class UseMap { public static void main(String[] args) { /* * Demonstrate how...
package datastructure; public class UseMap { public static void main(String[] args) { /* * Demonstrate how to use Map that includes storing and retrieving elements. * Add List<String> into a Map. Like, Map<String, List<string>> list = new HashMap<String, List<String>>(); * Use For Each loop and while loop with Iterator to retrieve data. * * Use any databases[MongoDB, Oracle, MySql] to store data and retrieve data. */ } }
Consider this program: public class Main { public static void main(String[] args) { String s1 =...
Consider this program: public class Main { public static void main(String[] args) { String s1 = "hello"; String s2 = "hello"; String s3 = new String("hello"); System.out.println(s1 == s2); System.out.println(s2 == s3); System.out.println(s2.equals(s3)); } } When we run the program, the output is: true false true Explain why this is the output, using words and/or pictures.
public class Main { public static void main(String [] args) { int [] array1 = {5,...
public class Main { public static void main(String [] args) { int [] array1 = {5, 8, 34, 7, 2, 46, 53, 12, 24, 65}; int numElements = 10; System.out.println("Part 1"); // Part 1 // Enter the statement to print the numbers in index 5 and index 8 // put a space in between the two numbers and a new line at the end // Enter the statement to print the numbers 8 and 53 from the array above //...
---------------------------------------------------------------------------- public class Main { public static void main(String[] args) { int[] A = {11, 12,...
---------------------------------------------------------------------------- public class Main { public static void main(String[] args) { int[] A = {11, 12, -10, 13, 9, 12, 14, 15, -20, 0}; System.out.println("The maximum is "+Max(A)); System.out.println("The summation is "+Sum(A)); } static int Max(int[] A) { int max = A[0]; for (int i = 1; i < A.length; i++) { if (A[i] > max) { max = A[i]; } } return max; } static int Sum(int[] B){ int sum = 0; for(int i = 0; i --------------------------------------------------------------------------------------------------------------------------- Convert...
public class Main{ public static void main (String[] args) { Map<Integer, String> ssnMap = new HashMap<Integer,...
public class Main{ public static void main (String[] args) { Map<Integer, String> ssnMap = new HashMap<Integer, String>(); ssnMap.put (8675309,"Jenney"); ssnMap.put (42, "Answer to Everything"); ssnMap.put (8675309, "Stacy"); ssnMap.put (1006, "Peter"); System.out.println(ssnMap.get (8675309)); } } What is the output of the above code. Why?
class Main { public static void main(String[] args) {        int[] array = {1,2,3,4,5};   ...
class Main { public static void main(String[] args) {        int[] array = {1,2,3,4,5};        //Complexity Analysis //Instructions: Print the time complexity of method Q1_3 with respect to n=Size of input array. For example, if the complexity of the //algorithm is Big O nlogn, add the following code where specified: System.out.println("O(nlogn)"); //TODO }    public static void Q1_3(int[] array){ int count = 0; for(int i = 0; i < array.length; i++){ for(int j = i; j < array.length;...
public class GreeterTest {    public static void main(String[] args)    { // create an object...
public class GreeterTest {    public static void main(String[] args)    { // create an object for Greeter class Greeter greeter = new Greeter("Jack"); // create two variables Greeter var1 = greeter; Greeter var2 = greeter; // call the sayHello method on the first Greeter variable String res1 = var1.sayHello(); System.out.println("The first reference " + res1); // Call the setName method on the secod Grreter variable var2.setName("Mike"); String res2 = var2.sayHello(); System.out.println("The second reference " + res2);    } }...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT