美文网首页
lintcode 165 合并两个排序链表

lintcode 165 合并两个排序链表

作者: jose_dl | 来源:发表于2017-08-07 20:57 被阅读0次
    Snip20170807_1.png
    • 思路
      两个链表都没到null的时候,要比较哪个被拆下来放到新链表中。
      head从l1,l2比较小的中找。然后就把那个链表后移一个位置。
      用r记录新链表的尾节点。拆,装贯穿整个过程
    /**
     * Definition for ListNode.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int val) {
     *         this.val = val;
     *         this.next = null;
     *     }
     * }
     */ 
    public class Solution {
        /**
         * @param ListNode l1 is the head of the linked list
         * @param ListNode l2 is the head of the linked list
         * @return: ListNode head of linked list
         */
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            // write your code here
            if(l1==null){
                return l2;
            }
            if(l2==null){
                return l1;
                
            }
            ListNode p=l1;
            ListNode q=l2;
            ListNode head=p.val<q.val?p:q;
            if(head==p){
                p=p.next;
            }else{
                q=q.next;
            }
            ListNode r = head;
           
            while(p !=null && q != null){
               if(p.val<q.val){
                    r.next=p;
                    r=p;
                    p=p.next;
               }
               else {
                    r.next=q;
                    r=q;
                    q=q.next;
               }
                
            }
            if(p!=null){
               r.next=p;
            }
            if(q!=null){
                r.next=q;
            }
            return head;
        }
    }
    

    相关文章

      网友评论

          本文标题:lintcode 165 合并两个排序链表

          本文链接:https://www.haomeiwen.com/subject/zutzlxtx.html