Question

In: Computer Science

Given two sorted linked lists, merge them into a third sorted linked list. If an element...

Given two sorted linked lists, merge them into a third sorted linked list. If an element is present in both the lists, it should occur only once in the third list.

Code needed in java.

Solutions

Expert Solution

The strategy here uses a temporary dummy node as the start of the result list. The pointer Tail always points to the last node in the result list, so appending new nodes is easy.
The dummy node gives the tail something to point to initially when the result list is empty. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either ‘a’ or ‘b’, and adding it to the tail. When
We are done, the result is in dummy.next.  

/* Java program to merge two
sorted linked lists */
import java.util.*;

/* Link list node */
class Node 
{
        int data;
        Node next;
        Node(int d) {data = d;
                                next = null;}
}
        
class MergeLists 
{
Node head; 

/* Method to insert a node at 
the end of the linked list */
public void addToTheLast(Node node) 
{
        if (head == null)
        {
                head = node;
        }
        else
        {
                Node temp = head;
                while (temp.next != null)
                        temp = temp.next;
                temp.next = node;
        }
}

/* Method to print linked list */
void printList()
{
        Node temp = head;
        while (temp != null)
        {
                System.out.print(temp.data + " ");
                temp = temp.next;
        } 
        System.out.println();
}


// Driver Code
public static void main(String args[])
{
        /* Let us create two sorted linked
        lists to test the methods 
        Created lists:
                llist1: 5->10->15,
                llist2: 2->3->20
        */
        MergeLists llist1 = new MergeLists();
        MergeLists llist2 = new MergeLists();
        
        // Node head1 = new Node(5);
        llist1.addToTheLast(new Node(5));
        llist1.addToTheLast(new Node(10));
        llist1.addToTheLast(new Node(15));
        
        // Node head2 = new Node(2);
        llist2.addToTheLast(new Node(2));
        llist2.addToTheLast(new Node(3));
        llist2.addToTheLast(new Node(20));
        
        
        llist1.head = new Gfg().sortedMerge(llist1.head, 
                                                                                llist2.head);
        llist1.printList();      
        
}
}

class Gfg
{
/* Takes two lists sorted in 
increasing order, and splices 
their nodes together to make 
one big sorted list which is 
returned. */
Node sortedMerge(Node headA, Node headB)
{
        
        /* a dummy first node to 
        hang the result on */
        Node dummyNode = new Node(0);
        
        /* tail points to the 
        last result node */
        Node tail = dummyNode;
        while(true) 
        {
                
                /* if either list runs out, 
                use the other list */
                if(headA == null)
                {
                        tail.next = headB;
                        break;
                }
                if(headB == null)
                {
                        tail.next = headA;
                        break;
                }
                
                /* Compare the data of the two
                lists whichever lists' data is 
                smaller, append it into tail and
                advance the head to the next Node
                */
                if(headA.data <= headB.data)
                {
                        tail.next = headA;
                        headA = headA.next;
                } 
                else
                {
                        tail.next = headB;
                        headB = headB.next;
                }
                
                /* Advance the tail */
                tail = tail.next;
        }
        return dummyNode.next;
}
}

Related Solutions

Given two integer arrays sorted in the ascending order, code the function SortArrays to merge them...
Given two integer arrays sorted in the ascending order, code the function SortArrays to merge them into one array in the descending order. You need to make sure if the values in the arrays are changed, it will still work. (25 points) #include using namespace std; void SortArrays (int a[], int b[], int c[], int size); void printArray(int m[], int length); const int NUM = 5; int main() { int arrA[NUM] = {-2, 31, 43, 55, 67}; int arrB[NUM] =...
Given two integer arrays sorted in the ascending order, code the function SortArrays to merge them...
Given two integer arrays sorted in the ascending order, code the function SortArrays to merge them into one array in the descending order. You need to make sure if the values in the arrays are changed, it will still work. (25 points) #include <iostream> using namespace std; void SortArrays (int a[], int b[], int c[], int size); void printArray(int m[], int length); const int NUM = 5; int main() { int arrA[NUM] = {-2, 31, 43, 55, 67}; int arrB[NUM]...
Given two integer arrays sorted in the ascending order, code the function SortArrays to merge them...
Given two integer arrays sorted in the ascending order, code the function SortArrays to merge them into one array in the descending order. You need to make sure if the values in the arrays are changed, it will still work. (25 points) #include <iostream> using namespace std; void SortArrays (int a[], int b[], int c[], int size); void printArray(int m[], int length); const int NUM = 5; int main() { int arrA[NUM] = {-2, 31, 43, 55, 67}; int arrB[NUM]...
Two sorted lists have been created, one implemented using a linked list (LinkedListLibrary linkedListLibrary) and the...
Two sorted lists have been created, one implemented using a linked list (LinkedListLibrary linkedListLibrary) and the other implemented using the built-in Vector class (VectorLibrary vectorLibrary). Each list contains 100 books (title, ISBN number, author), sorted in ascending order by ISBN number. Complete main() by inserting a new book into each list using the respective LinkedListLibrary and VectorLibrary InsertSorted() methods and outputting the number of operations the computer must perform to insert the new book. Each InsertSorted() returns the number of...
C++ Question Create two circular linked lists and find their maximum numbers. Merge the two circular...
C++ Question Create two circular linked lists and find their maximum numbers. Merge the two circular linked lists such that the maximum number of 2nd circular linked list immediately follows the maximum number of the 1st circular linked list. Input: 12 -> 28 -> 18 -> 25 -> 19-> NULL 5 -> 24 -> 12 -> 6 -> 15-> NULL Output: 28 -> 24-> 25 -> 15 -> 19 -> 15->5-> 18 -> 25 -> 19->NULL Note:- Code should work...
C++ language or Python. Linked Lists You are given a linked list that contains N integers....
C++ language or Python. Linked Lists You are given a linked list that contains N integers. You are to perform the following reverse operation on the list: Select all the subparts of the list that contain only even integers. For example, if the list is {1,2,8,9,12,16}, then the selected subparts will be {2,8}, {12,16}. Reverse the selected subpart such as {8,2} and {16,12}. The list should now be {1,8,2,9,16,12}. Your node definition should consist of 2 elements: the integer value...
C++ Linked Lists Practice your understanding of linked lists in C++ by creating a list of...
C++ Linked Lists Practice your understanding of linked lists in C++ by creating a list of songs/artist pairs. Allow your user to add song / artist pairs to the list, remove songs (and associated artist) from the list and be sure to also write a function to print the list! Have fun! Make sure you show your implementation of the use of vectors in this lab (You can use them too ) You MUST modularize your code ( meaning, there...
(Java) Create a new linked list from two given arrays with the greater element from each...
(Java) Create a new linked list from two given arrays with the greater element from each corresponding array element placed into the linked list. Given two arrays of varying size initialized with integers of varying values, the task is to create a new linked list using those arrays. The condition is that the greater element value from each corresponding array element will be added to the new linked list in the list position that maintains the integers in ascending order....
Write and test a merge function that uses a recursive algorithm to merge two sorted arrays...
Write and test a merge function that uses a recursive algorithm to merge two sorted arrays of integers. Neither list contains duplicates, and the resulting list should not contain duplicates either. Hint: You may want to call a helper function from merge. PROGRAM: C
concatenate(lst1, lst2 ) Given two (possibly empty) unordered lists, concatenate them such that the first list...
concatenate(lst1, lst2 ) Given two (possibly empty) unordered lists, concatenate them such that the first list comes first.Example: When the first input unordered list lst1 is [1, 2, 3] and the second lst2 is [7,8,9], the outputunordered list is [1,2,3,7,8,9]. Use codes: class Node: def __init__(self, data): self.data = data self.next = None def getData(self): return self.data def getNext(self): return self.next def setData(self, data): self.data = data def setNext(self, node): self.next = node class UnorderedList: def __init__(self): self.head = None...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT