Welcome everyone

每周一练(23)

每周一练 汪明鑫 236浏览 0评论

输入两个有序的链表,输出两个链表合成后的有序链表。

 

package pers.wmx.practice.linkedlist;

/**
 * @author: wangmingxin03
 * @date: 2020-06-03
 */
public class MergeLinkedList {

    public ListNode Merge(ListNode list1,ListNode list2) {
        ListNode head = new ListNode(-1);
        head.next = null;

        //合并的链表
        ListNode mergeList = head;
        ListNode p = list1;
        ListNode q = list2;

        while(p != null && q != null){
            if(p.var < q.var){
                head.next = p;
                head = p;
                p = p.next;
            }else{
                head.next = q;
                head = q;
                q = q.next;
            }
        }

        if(p != null){
            head.next = p;
        }

        if(q != null){
            head.next=q;
        }

        return mergeList.next;
    }

}

 

 

转载请注明:汪明鑫的个人博客 » 每周一练(23)

喜欢 (2)

说点什么

您将是第一位评论人!

提醒
avatar
wpDiscuz