lintcode 165 合并两个排序链表

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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容