Question

Please solve using java.

21. Merge Two Sorted Lists Easy 2705 396 ♡ Favorite Sha * Definition for singly-linked list. * public class ListNode { int va

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

Here is the completed code for this problem. This code alters the input lists by rearranging the links, not creating new nodes. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

class Solution {

      // required method

      public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

            // creating a ListNode reference to store the head of sorted list

            ListNode root = null;

            // creating a ListNode reference to store the current node of sorted

            // list

            ListNode current = null;

            // looping as long as l1 and l2 are not null

            while (l1 != null && l2 != null) {

                  // comparing value of l1 with value of l2

                  if (l1.val <= l2.val) {

                        // if current is null,setting l1 as current & root nodes

                        if (current == null) {

                              current = l1;

                              root = current;

                        } else {

                              // otherwise, setting l1 as next node of current and

                              // advancing current

                              current.next = l1;

                              current = current.next;

                        }

                        // moving to next node in l1

                        l1 = l1.next;

                  } else {

                        // doing the same with l2

                        if (current == null) {

                              current = l2;

                              root = current;

                        } else {

                              current.next = l2;

                              current = current.next;

                        }

                        l2 = l2.next;

                  }

            }

            // after the loop, if l1 is not null, appending l1 to current, if l2 is

            // not null, appending l2 to current. this is needed in case lists have

            // unequal lengths

            if (l1 != null) {

                  if (current == null) {

                        current = l1;

                        root = current;

                  } else {

                        current.next = l1;

                  }

            }

            if (l2 != null) {

                  if (current == null) {

                        current = l2;

                        root = current;

                  } else {

                        current.next = l2;

                  }

            }

            //returning head of root node of merged list

            return root;

      }

}

Add a comment
Answer #2
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {        
        //Define a new Node
        ListNode answer = new ListNode();
        ListNode newNode = answer;        
        //If list1 has no element then add list2 to new node
        if (list1 == null)           return newNode.next = list2;        
        //If list2 has no element then add list1 to new node
        if (list2 == null)            return newNode.next = list1;        
        
        //Use Merge sort logic to merge nodes value
        while (list1 != null && list2 != null)
        {            if (list1.val <= list2.val)
            {
                newNode.next = list1;
                list1 = list1.next;
            }            else 
            {
                newNode.next = list2;
                list2 = list2.next;
            }
            newNode = newNode.next;
        }    
        //If any node left in list1
        if (list1 != null)
            newNode.next = list1;     
        //If any node left in list2
        if (list2 != null)
            newNode.next = list2;        
        return answer.next;

    }
}


answered by: Shivani Sharma
Add a comment
Know the answer?
Add Answer to:
Please solve using java. 21. Merge Two Sorted Lists Easy 2705 396 ♡ Favorite Sha *...
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
  • Could somebody please help. Thanks in advance! Merge two sorted linked lists and return it as...

    Could somebody please help. Thanks in advance! Merge two sorted linked lists and return it as a new list. 1) Implement a method: mergeTwoLists(…){…} 2) Use the LinkedList library in Java 3) Test your method. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 ````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` import java.util.*; public class Inclass1 { public static void main(String[] args){ //Question 5.2 LinkedList l1 = new LinkedList<>(); LinkedList l2 = new LinkedList<>(); l1.add(1); l1.add(2); l1.add(10); l2.add(1); l2.add(3); l2.add(4); LinkedList l3 = mergeTwoLists(l1, l2); System.out.println("Question \n******************************"); for(int i...

  • (20 points) ) Write a Python program which merges two sorted singly linked lists and return...

    (20 points) ) Write a Python program which merges two sorted singly linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Example: Input: 1->2- >4, 1->3->4 Output: 1->1->2->3 ->4->4

  • JAVA lists and nodes my answer was : ListNode newNode = new ListNode(3); newNode.next = head;...

    JAVA lists and nodes my answer was : ListNode newNode = new ListNode(3); newNode.next = head; head = newNode; it is incorrect. what could it be? linkedNodes 11 > <linkedNodes 9 Main Page -- Problems - Solve a Problem OBJP5 Self-Check 16.10: linkedNodes 10 Language/Type: Java ListNodes LinkedLists Related Links: LinkedIntList.java Author: Marty Stepp (on 2019/09/19) Write the code necessary to convert the following sequence of ListNode objects: list -> [1] -> [2] / Into this sequence of ListNode objects:...

  • Please help me to solve the problem with java language! An implementation of the Merge Sort...

    Please help me to solve the problem with java language! An implementation of the Merge Sort algorithm. Modify the algorithm so that it splits the list into 3 sublists (instead of two). Each sublist should contain about n/3 items. The algorithm should sort each sublist recursively and merge the three sorted sublists. The traditional merge sort algorithm has an average and worst-case performance of O(n log2 n). What is the performance of the 3-way Merge Sort algorithm? Merge Sort algorithm...

  • Write a method public static ArrayList merge(ArrayList a, ArrayList b) that merges two array lists, alternating...

    Write a method public static ArrayList merge(ArrayList a, ArrayList b) that merges two array lists, alternating elements from both array lists. If one array list is shorter than the other, then alternate as long as you can and then append the remaining elements from the longer array list. For example, if a is 1 4 9 16 and b is 9 7 4 9 11 then merge returns the array list 1 9 4 7 9 4 16 9 11...

  • if we have following List classes: public class LinkedList<T> { class ListNode { protected T value;...

    if we have following List classes: public class LinkedList<T> { class ListNode { protected T value; protected ListNode next; public ListNode(T val, ListNode nxt) { value = val; next = nxt; } public ListNode(T val) { this(val, null); } public ListNode() { this(null, null); } } can you write the folowing methods in java: 1.Write a method for the LinkedList class called int indexOf(T val) which returns the integer index indicating the location of val in the list, or -1...

  • c++ programming please. thx. Define a function template named "merge" to merge two lists of items...

    c++ programming please. thx. Define a function template named "merge" to merge two lists of items into one list including all the items of the first list followed by the items of the second list. Even though, the data type of the items of the lists is a generic type, both input lists include items of the same type. To merge the two lists, the function first dynamically allocates enough memory to accommodate the items of both lists. The allocated...

  • Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to...

    Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to both classes: public void reverseThisList(), This method will reverse the lists. When testing the method: print out the original list, call the new method, then print out the list again ------------------------------------------------------------------------- //ARRAY LIST class: public class ArrayList<E> implements List<E> { /** Array of elements in this List. */ private E[] data; /** Number of elements currently in this List. */ private int size; /**...

  • C++ Create a class that implements a sorted, doubly-linked list: Start with a copy of the...

    C++ Create a class that implements a sorted, doubly-linked list: Start with a copy of the sortedList class. Call your new class doublyLinkedList. Convert the baseline code into a doubly linkedlist, and thoroughly test all existing operations (make sure to check all edge conditions), and then implement the new operations below. The class should have the following additional class methods: • A reverse method: this method will reverse the order of the doubly linked list. This method takes no parameters,...

  • Need the answers to these RECURSIVE practice problems using Linked Lists in JAVA . Thank you. Complete the Link cl...

    Need the answers to these RECURSIVE practice problems using Linked Lists in JAVA . Thank you. Complete the Link class by writing methods described below. Do not use loops, or create any more methods (other than those specified), class or instance variables. public class Link private Link next; /null if this is the last link private int value; public Link(Link n, int v) nextn valuev; Do not use loops, or create any more methods (other than those specified), class or...

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