Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Add avoidmethodaddInOrderto theLinkedListclass which takes an integervalas a parameter. It should find the correct location in the already-sorted (lowest to highest) list forval, then make

Add a void method addInOrder to the LinkedList class which takes an integer val as a parameter. It should find the correct location in the already-sorted (lowest to highest) list for val, then make a new node with val as its data, correctly connecting it into the list. It should complete without exceptions, regardless of where val needs to be located in the list or how many items are in the list already.

 

Note: You may feel free to add any helper methods you would like to the class or use any existing class methods. You are also permitted to call any of the methods from the starter code if they would be helpful to your solution.

 

 

public class LinkedList{

 

   public class Node{ //inner class

       int data;

       Node next;

       Node prev;

 

       public Node(int data){

           this.data = data;

       }

   }

   

   public Node head;

   public Node tail;

 

   public LinkedList(){

       head = null;

       tail = null;

   }

   

   // YOUR CODE HERE

 

   public void addHead( int data ){

       Node n = new Node( data );

       if(head == null){ //empty list

           tail = n;

       }

       else{

           head.prev = n;

       }

       n.next = head;

       

       head = n;

   }

 

   public void addTail( int data ){

       Node n = new Node( data );

       if(tail == null){ //empty list

           head = n;

       }

       else{

           tail.next = n;

       }

       n.prev = tail;

       tail = n;

   }

   

   public Node getHead() {

       return head;

   }

   

   public Node getTail() {

       return tail;

   }

   

   public String toString() {

       String res = "";

       

       Node curr = head;

       

       if (curr != null) {

           res += curr.data;

           curr = curr.next;

       }

       

       while (curr != null) {

           res += ", " + curr.data;

           curr = curr.next;

       }

 

       return res;

   }

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

To implement the addInOrder method in the LinkedList class you can follow these steps Create a new node with the given val as its data Check if the li... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Elements Of Chemical Reaction Engineering

Authors: H. Fogler

6th Edition

013548622X, 978-0135486221

More Books

Students also viewed these Programming questions