Merging two sorted linked lists is a common problem that can be solved efficiently. Here's how you can do it in a simple and optimal way using Java.
class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; this.next = null; } } public class LinkedList { // Function to merge two sorted linked lists public ListNode mergeTwoLists(ListNode l1, ListNode l2) { // Create a dummy node to act as the starting point ListNode dummy = new ListNode(0); ListNode current = dummy; // Traverse both lists and compare nodes while (l1 != null && l2 != null) { if (l1.val <= l2.val) { current.next = l1; l1 = l1.next; } else { current.next = l2; l2 = l2.next; } current = current.next; } // If one list is exhausted, link the remaining nodes of the other list if (l1 != null) { current.next = l1; } else { current.next = l2; } // The merged list starts from the next node of the dummy node return dummy.next; } // Function to print the linked list public void printList(ListNode head) { ListNode temp = head; while (temp != null) { System.out.print(temp.val + " "); temp = temp.next; } System.out.println(); } public static void main(String[] args) { LinkedList list = new LinkedList(); // Create first sorted linked list: 1 -> 3 -> 5 ListNode l1 = new ListNode(1); l1.next = new ListNode(3); l1.next.next = new ListNode(5); // Create second sorted linked list: 2 -> 4 -> 6 ListNode l2 = new ListNode(2); l2.next = new ListNode(4); l2.next.next = new ListNode(6); System.out.println("First List:"); list.printList(l1); System.out.println("Second List:"); list.printList(l2); // Merge the two lists ListNode mergedList = list.mergeTwoLists(l1, l2); System.out.println("Merged List:"); list.printList(mergedList); } }
ListNode Class:
mergeTwoLists Method:
printList Method:
main Method:
This method is both simple and optimal for merging two sorted linked lists, ensuring efficient and clean code.
The above is the detailed content of Merge two sorted linked lists in java simple and optimal way. For more information, please follow other related articles on the PHP Chinese website!