Question 21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
中文:合并两个有序的链表,然后返回新的链表。新的链表应该是拼接的前面两个链表。
链表结点的定义:
//结点: public class ListNode { public int val; public ListNode next; ListNode(int x) { val = x; } }实现思路: 1)判断l1和l2是否存在空链表,有空链表就可以直接返回。
2)找出l1和l2中最小的结点,作为新链表的表头结点。
3)然后依次比较遍历l1和l2,将较小的结点插入在新链表的后面。
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null ){ return l2; } if(l2 == null){ return l1; } if(l1==null && l2 == null){ return null; } /** l1和l2均非空 */ ListNode p1 = l1; ListNode p2 = l2; //先找出l1和l2的头结点中 较小的结点作为新链表的head ListNode head=null; if(l1.val<l2.val){ head = l1; p1 = p1.next; }else { head = l2; p2 = p2.next; } //新链表的p指针 ListNode p = head; //当p1和p2都不为空时 while (p1!=null && p2 !=null){ if(p1.val < p2.val){ p.next = p1; p = p.next; p1 = p1.next; } else { p.next = p2; p = p.next; p2 = p2.next; } } if(p1 == null && p2 == null){ return head; }else if(p1 == null && p2 != null){ p.next = p2; }else if(p2 == null && p1 != null){ p.next = p1; } return head; }一次Accept。
