/** * 题目: * 提供两个有序的整数链表,请返回一个合并后的有序链表。 * 编写测试用例验证你的代码。 * * 示例: * ``` * Input: 1->2->4, 1->3->4 * Output: 1->1->2->3->4->4 * ``` */ public class ShowMeBug { public static class ListNode { int val; ListNode next;
ListNode(int x) { val = x; } } public static ListNode solution(ListNode l1, ListNode l2) { ListNode cur = new ListNode(0); ListNode node = cur; while(l1!=null && l2 !=null){ if(l1.val<=l2.val){ node.next =l1; node = node.next; l1 = l1.next; }else{ node.next = l2; node = node.next; l2 = l2.next; } } if(l1 == null){ node.next = l2; }else{ node.next = l1; } return cur.next; } public static void main(String[] args) { System.out.println("开始测试"); ListNode head1 = new ListNode(1); ListNode node1 = new ListNode(2); ListNode node2 = new ListNode(4); ListNode node3 = new ListNode(3); ListNode node4 = new ListNode(4); ListNode head2 = new ListNode(1);
head1.next = node1; node1.next =node2; head2.next = node3; node3.next = node4; node3.next = node4; ListNode result = solution(head1,head2); while(result !=null){ System.out.println(result.val); result = result.next; } } }