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.

思路: 新生成的链表指向第一条链表

java代码:

  1. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  2. if(l1==null) return l2;
  3. if(l2==null) return l1;
  4. ListNode dummy = new ListNode(-1);
  5. ListNode p=dummy;
  6. p.next = l1;
  7. while(l1!=null&&l2!=null) {
  8. if(l2.val < l1.val) {
  9. p.next = l2;
  10. l2 = l2.next;
  11. } else {
  12. l1 = l1.next;
  13. }
  14. p = p.next;
  15. p.next = l1;
  16. }
  17. if(l2!=null) {
  18. p.next = l2;
  19. }
  20. return dummy.next;
  21. }
posted @ 2014-07-25 10:53  purejade  阅读(73)  评论(0)    收藏  举报