leetcode 21. Merge Two Sorted Lists

来源:互联网 发布:浙江海正药业待遇知乎 编辑:程序博客网 时间:2024/06/13 08:29

题目

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.

解1

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        if(l1==null && l2==null){            return null;        }        if(l1==null && l2!=null){            return l2;        }        if(l1!=null && l2==null){            return l1;        }        ListNode p=l1;        ListNode q=l2;        ListNode head=null;        ListNode end=null;        ListNode base=null;//指向head的指针        if(p.val<=q.val){            head=l1;            p=p.next;        }else{            head=l2;            q=q.next;        }        base=head;        while(p!=null&&q!=null){            if(p.val<=q.val){                base.next=p;                p=p.next;            }else{                base.next=q;                q=q.next;            }                       base=base.next;        }        if(p!=null){            base.next=p;        }        if(q!=null){            base.next=q;        }        return head;    }}

解2(优解)

   public ListNode mergeTwoLists(ListNode l1, ListNode l2) {//递归的方式        if(l1==null){            return l2;        }else if(l2==null)            return l1;        ListNode pMergeHead=null;        if(l1.val<l2.val){            pMergeHead=l1;            pMergeHead.next=mergeTwoLists(l1.next,l2);        }else{            pMergeHead=l2;            pMergeHead.next=mergeTwoLists(l1,l2.next);        }        return pMergeHead;    }
0 0
原创粉丝点击