有序链表归并

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/muzhixi/article/details/89326927

常规题目。

需要注意的点:判空。

    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1==null&&list2==null) return null;
        else if(list1==null&&list2!=null) return list2;
        else if(list1!=null&&list2==null) return list1;
        ListNode pointer1,pointer2,newList,newLast,curNode;
        pointer1=list1;
        pointer2=list2;
        if(pointer1.val<=pointer2.val){//确定头结点
            newList=pointer1;
            pointer1=pointer1.next;
            newList.next=null;
            newLast=newList;
        }
        else {
            newList=pointer2;
            pointer2=pointer2.next;
            newList.next=null;
            newLast=newList;
        }
        while(pointer1!=null&&pointer2!=null){//归并
            if(pointer1.val<=pointer2.val){
                curNode=pointer1;
                pointer1=pointer1.next;
                newLast.next=curNode;
                newLast=newLast.next;
                newLast.next=null;
            }
            else {
                curNode=pointer2;
                pointer2=pointer2.next;
                newLast.next=curNode;
                newLast=newLast.next;
                newLast.next=null;
            }
        }
        if(pointer1!=null) newLast.next=pointer1;//将剩余部分接上
        if(pointer2!=null) newLast.next=pointer2;
        return newList;
    }

猜你喜欢

转载自blog.csdn.net/muzhixi/article/details/89326927