合并两个排序链表是一个可以有效解决的常见问题。以下是如何使用 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中文网其他相关文章!