合併兩個排序鍊錶是一個可以有效解決的常見問題。以下是如何使用 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 類別:
mergeTwoLists 方法:
printList 方法:
主要方法:
此方法既簡單又適合合併兩個排序的鍊錶,確保程式碼有效率且乾淨。
以上是用java簡單且最佳的方式合併兩個排序的鍊錶的詳細內容。更多資訊請關注PHP中文網其他相關文章!