Question:
How to find merge two sorted linked list in Reverse Order using Java

Summary

Here we will make sure that the function ‘mergeResult’ merge two sorted link list in ascending order. The following are the ways you can use in your code:


Handling of Edge Classes: You can consider explicitly handling cases where both or at least one input link lists are empty. 


Code simplification: You can simply your code by using one loop instead of using two. Thus, making the code easier and cleaner. 


Variable Naming: Name your variable in a more descriptive manner. This will enhance your code and its readability. 


Solution

#User function Template for python3


#User function Template for python3


'''

class Node:

    def __init__(self,data):

        self.data=data

        self.next=None

'''


class Solution:

    def mergeResult(self, h1, h2):

        #return head of merged list

        if not h1 and not h2:return

        if h1 == None:

            return self.reverse(h2)

        if h2 == None:

            return self.reverse(h1)

        cur1, cur2 = h1, h2

        temp1, temp2 = None, None

        ans = None

        while cur1 and cur2:

            if cur1.data >= cur2.data:

                if not ans:

                    ans = cur2

                prev = None

                while cur2 and cur2.data <= cur1.data:

                    prev = cur2

                    cur2 = cur2.next

                temp2 = prev.next

                prev.next = cur1

                cur2 = temp2

            else:

                if not ans:

                    ans = cur1

                prev = None

                while cur1 and cur1.data <= cur2.data:

                    prev = cur1

                    cur1 = cur1.next

                temp1 = prev.next

                prev.next = cur2

                cur1 = temp1

        return self.reverse(ans)

        

    def reverse(self, head):

        prev = None

        while head:

            temp = head.next

            head.next = prev

            prev = head

            head = temp

        return prev


Suggested blogs:

>Find the number of pairs of elements whose sum is equal to K using C++

>How to check whether string is palindrome or not using C++

>How to determine the smallest possible size of a vertex cover using C++

>How to reverse the first K elements of queue using C++

>How to find duplicate rows in a binary matrix using C++

>How to find the total number of special sequences possible using C++

>How to Reverse array in groups? C++

>How to represent the maximum value in knapsack using C++


Nisha Patel

Nisha Patel

Submit
0 Answers