21. 合并两个有序链表

题目:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

代码:

/**

  • Definition for singly-linked list.

  • public class ListNode {

  • int val;
    
  • ListNode next;
    
  • ListNode() {}
    
  • ListNode(int val) { this.val = val; }
    
  • ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    
  • }
    */
    class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    ListNode pl1=l1;
    ListNode pl2=l2;
    ListNode res=new ListNode();
    ListNode p=res;
    while(pl1!=null&&pl2!=null){
    if(pl1.val<pl2.val){ //按大小插入
    p.next=pl1;
    p=p.next;
    pl1=pl1.next;
    }else{
    p.next=pl2;
    p=p.next;
    pl2=pl2.next;
    }
    }
    if(pl1null){ //pl2还有余节点点l
    p.next=pl2;
    }
    if(pl2
    null){ //pl1还有余节点点l
    p.next=pl1;

    }
    return res.next;
    }
    }

posted @ 2020-12-05 10:15  堤苏白  阅读(39)  评论(0)    收藏  举报