一、题目

Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.

Example

Given 1->3->8->11->15->null, 2->null , return 1->2->3->8->11->15->null.

将两个排序链表合并为一个新的排序链表

二、解题思路

只需要从头开始比较已排序的两个链表,新链表指针每次指向值小的节点,依次比较下去,最后,当其中一个链表到达了末尾,我们只需要把新链表指针指向另一个没有到末尾的链表此时的指针即可。

三、解题代码

  1. /**
  2. * Definition for ListNode.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int val) {
  7. * this.val = val;
  8. * this.next = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. /**
  14. * @param ListNode l1 is the head of the linked list
  15. * @param ListNode l2 is the head of the linked list
  16. * @return: ListNode head of linked list
  17. */
  18. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  19. ListNode dummy = new ListNode(0);
  20. ListNode curr = dummy;
  21. while ((l1 != null) && (l2 != null)) {
  22. if (l1.val > l2.val) {
  23. curr.next = l2;
  24. l2 = l2.next;
  25. } else {
  26. curr.next = l1;
  27. l1 = l1.next;
  28. }
  29. curr = curr.next;
  30. }
  31. // link to non-null list
  32. curr.next = (l1 != null) ? l1 : l2;
  33. return dummy.next;
  34. }
  35. }