Merge Two Sorted Lists

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.
I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
LeetCode Problem - 21
/**
* Definition for singly-linked list.
* public class ListNode {
* int val; // value stored in the node
* ListNode next; // reference to the next node in the list
* ListNode() {} // default constructor
* ListNode(int val) { this.val = val; } // constructor with value only
* ListNode(int val, ListNode next) { this.val = val; this.next = next; } // constructor with value and next node
* }
*/
class Solution {
// Method to merge two sorted linked lists into one sorted list
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
// Create a list to store the values of both linked lists
List<Integer> list = new ArrayList<>();
// Temporary pointer to traverse the first list (list1)
ListNode tempHead = list1;
// Traverse list1 and add each value to the list
while(tempHead != null){
list.add(tempHead.val);
tempHead = tempHead.next;
}
// Reset tempHead to traverse the second list (list2)
tempHead = list2;
// Traverse list2 and add each value to the list
while(tempHead != null){
list.add(tempHead.val);
tempHead = tempHead.next;
}
// If both lists are empty, return null (no nodes to merge)
if(list.isEmpty()) return null;
// Sort the list containing values from both linked lists
Collections.sort(list);
// Create the head of the new merged sorted linked list
ListNode answer = new ListNode(list.get(0));
// Pointer to traverse and build the merged list
ListNode answerHead = answer;
// Create the rest of the merged list from the sorted values
for(int i = 1; i < list.size(); i++){
answerHead.next = new ListNode(list.get(i)); // add the next value
answerHead = answerHead.next; // move the pointer to the next node
}
// Return the head of the merged sorted linked list
return answer;
}
}




