【Leetcode】Merge Two Sorted Lists

来源:互联网 发布:c语言windows窗口程序 编辑:程序博客网 时间:2024/06/18 10:35

题目链接:https://leetcode.com/problems/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.

思路:

easy 。

算法:

[java] view plain copy
  1. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {  
  2.     ListNode head = null, l, p = l1, q = l2;  
  3.     // ==确定头节点  
  4.     if (p != null && q != null) {  
  5.         if (p.val < q.val) {  
  6.             head = p;  
  7.             p = p.next;  
  8.         } else {  
  9.             head = q;  
  10.             q = q.next;  
  11.         }  
  12.     } else if (p == null) {  
  13.         head = q;  
  14.         return head;  
  15.     } else if (q == null) {  
  16.         head = p;  
  17.         return head;  
  18.     }  
  19.     l = head;  
  20.     // ===end  
  21.   
  22.     while (p != null && q != null) {  
  23.         if (p.val < q.val) {  
  24.             l.next = p;  
  25.             l = p;  
  26.             p = p.next;  
  27.         } else {  
  28.             l.next = q;  
  29.             l = q;  
  30.             q = q.next;  
  31.         }  
  32.     }  
  33.   
  34.     if (p == null) {  
  35.         l.next = q;  
  36.     } else if (q == null) {  
  37.         l.next = p;  
  38.     }  
  39.   
  40.     return head;  
  41. }  


0 0
原创粉丝点击