Question

In Java im trying to use a recursive wrapper method for inserting a node in a...

In Java im trying to use a recursive wrapper method for inserting a node in a linkedlist in order but Im having trouble figuring out how to sort these nodes. Any help would be greatly appreciated.

private Node insert(int key, Node head) {

       if(!find(key)) {
           /**
           if(key > head.data && head.link == null) {
               Node curr = new Node(key);
               head.link = curr;
               return curr = head;
           }

           if(key > head.data) {
               return insert(key, head.link);
           }
           if(key < head.data) {
               Node temp = head;
               head = new Node(key);
               return head.link = temp;
           }
           **/
           Node curr = new Node(key);

           curr.link = head;

           head = curr;
       }


       return insert(key, head.link);
   }

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Dear Student,

As you want to store or insert the key values in linked list in sorted order. Hence I am considering this to be sorted in ascending order.

Since you have just shared only insert function not complete program of Linked List. So, I have created the same scenario but inside find method I am returning false always (considering that value is not present in linked list, even though we can insert the same value again and again). So, I am not re-writing the complete logic of find method because here the main focus is our insert method which should store the keys into the linked list in sorted order . If you need complete program with proper find method, please let me know in comments section and share the complete code snippet which you have created.

Screensbot of insert method is as below:-

Screenshot of complete program is mentioned below which I have made. Your complete program may be different from my program as I have just created this Linked List program to reproduce the issue which you were getting while inserting values in sorted order into the linked list.

Note:- You just need to replace your insert method to the method I have shared above.

Complete prgram in textual format is mentioned below. Insert method is shown in bold:-

class Node {
   public Node link;
   public int data;
   public Node(int data) {
       this.data=data;
   }
}

public class LinkedList {


   private Node insert(int key, Node head) {
       //Insert only if key is not present
       if(!find(key)) {
           /*
           * Create Node class object only when you will get either value of head as null that
           * means that you are going to create first object of the list class or the node whose
           * key value is greater than the key value which we want to insert
           */
           if (head == null || head.data >= key) {
               //Create node class object
               Node node=new Node(key);
               //Set node link as head
               node.link = head;
              
               //return the newly inserted node
               return node;
           }
       }
       /* Otherwise recursive call insert function with the next node as head*/
       head.link= insert(key,head.link);
       return head;
   }

  
   public static void main(String[] args) {
       Node head=null;
       LinkedList linkedList=new LinkedList();
      
       /*Inserting the value 10 inside linked list as first node
       Since this is first node which will going to insert,
       Hence I am assigning the head value to the first node*/
       head=linkedList.insert(10, head);
      
       //Inserting 20 to the linked list and reassigning the head value
       head=linkedList.insert(20, head);
      
       //Inserting 7 to the linked list and reassigning the head value
       head=linkedList.insert(7, head);
      
       //Inserting 15 to the linked list and reassigning the head value
       head=linkedList.insert(15, head);
      
       //Inserting 14 to the linked list and reassigning the head value
       head=linkedList.insert(14, head);

       //Traversing the linked list
       System.out.println("Our Linked List in sorted order is as below:-");
       while(head!=null) {
           System.out.println(head.data);
           head=head.link;
       }
   }

   private boolean find(int key) {
       return false;
   }

}

Output of the above program is below. In the below screenshot we can see that the value we are getting in sorted order but in above program you can see that the order in which i am inserting the values are 10, 20, 7, 15, 14:-

Note:-

1. Most of the code contains the comments for your ready refrence.

2. Still, I am repeating that your complete code may be differed from my code. So you just need to replace the insert method code which I have shared above in bold.

Still, if you need any help. Please feel free to reach me through comments section. I will try to reply as early as possible.

Thanks!!

Add a comment
Know the answer?
Add Answer to:
In Java im trying to use a recursive wrapper method for inserting a node in a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • JAVA you have been given the code for Node Class (that holds Strings) and the LinkedList...

    JAVA you have been given the code for Node Class (that holds Strings) and the LinkedList Class (some methods included). Remember, you will use the LinkedList Class that we developed in class not Java’s LinkedList Class. You will add the following method to the LinkedList Class: printEvenNodes – this is a void method that prints Nodes that have even indices (e.g., 0, 2, 4, etc). Create a LinkedListDemo class. Use a Scanner Class to read in city names and store...

  • I am trying to make a linked list queue and I am trying to use the...

    I am trying to make a linked list queue and I am trying to use the display method I made just to see if its working but when I run it nothing is displayed please help. Also the newPlane boolean was made just so I can randomly decide if the plane is going to join the queue or not. public class PlaneSimulation { public static void main(String[] args) { int landTime = 2; int takeoffTime = 3; int avgArrivalInterval =...

  • (C++) You are tasked with implementing a recursive function void distanceFrom(int key) on the IntList class...

    (C++) You are tasked with implementing a recursive function void distanceFrom(int key) on the IntList class (provided). The function will first search through the list for the provided key, and then, recursively, change all previous values in the list to instead be their distance from the node containing the key value. Do not update the node containing the key value or any nodes after it. If the key does not exist in the list, each node should contain its distance...

  • You are tasked with implementing a recursive function void distanceFrom(int key) on the IntList class (provided)....

    You are tasked with implementing a recursive function void distanceFrom(int key) on the IntList class (provided). The function will first search through the list for the provided key, and then, recursively, change all previous values in the list to instead be their distance from the node containing the key value. Do not update the node containing the key value or any nodes after it. If the key does not exist in the list, each node should contain its distance from...

  • I need help with todo line please public class LinkedList { private Node head; public LinkedList()...

    I need help with todo line please public class LinkedList { private Node head; public LinkedList() { head = null; } public boolean isEmpty() { return head == null; } public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.getNext(); } return count; } public void add(int data) { Node newNode = new Node(data); newNode.setNext(head); head = newNode; } public void append(int data) { Node newNode = new Node(data);...

  • iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains...

    iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains a loop. Print true if yes, false if not. Test by using the following code: LL<Integer> L = new LL<>(); for (int i = 1000; i > 0; i-=3) sl.add(i); try { L.insert(122, L.getNode(70), L.getNode(21)); if (L.detectLoop()) System.out.println("True"); else System.out.println("False."); } catch(Exception e){ e.printStackTrace(); } class Linkedlist<E>{ private static class Node<E>{ private E element; private Node<E> next; public Node(E e, Node<E> n){ element =...

  • Your task is to complete the following function/functions: 1. Given a position in the linked list,...

    Your task is to complete the following function/functions: 1. Given a position in the linked list, delete the node at that position.(Silver problem - Mandatory ) 2. Print the sum of all negative elements in the linked list.(Gold problem) If you want, you can refer to the the previous recitation manual (which was on Linked Lists) to implement node deletion. #include <iostream> using namespace std; //----------- Define Node --------------------------------------------------- struct Node{ int key; Node *next; }; //----------- Define Linked List...

  • C++ 1. Please use attached script for your reference to create the node structure and a...

    C++ 1. Please use attached script for your reference to create the node structure and a linked list class, say LinkedList, that has the following basic member methods:     constructor, destructor//IMPORTANT, display(), add_node(). 2. Please implement the following additional member methods:     Please feel free to change T with any data type you'd like to use for your node stricture's data type. -- addFirst(T data) // Adds an node with data at the beginning of the list -- pop() //...

  • ^^^ Q3. I am trying to implement double linked list but I was failed to write...

    ^^^ Q3. I am trying to implement double linked list but I was failed to write the code so anyone gives the main Code in the main function   THANK YOU FOR ADVANCE #include<stdio.h> #include<stdlib.h> #include<alloc.h> struct node {      int info;      struct node *lptr,*rptr; }; typedef struct node DL; DL *delete( ) , *insert ( ); void display(); DL *delete(DL *start,int x) {      DL *left,*right,*curr;      curr = start;      if( start == NULL)       {                 printf("\nDoubly...

  • // 1. Add methods to get and set, Data and Link. Data should be any Comparable...

    // 1. Add methods to get and set, Data and Link. Data should be any Comparable object. class Node { Integer data; // Integer is Comparable Node link; public Node(Integer data, Node link) { this.data = data; this.link = link; } public Integer getData() { return data; } public void setData(Integer data) { this.data = data; } public Node getLink() { return link; } public void setLink(Node link) { this.link = link; } } // b. Create MyLinkedList class and...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT