非遞歸實現兩個有序鏈表

public ListNode Merge(ListNode list1,ListNode list2) {
        //用mHead標識新鏈表的頭結點
        //用c標識新鏈表的最後一個節點
        //用list1,list2遍歷兩個鏈表
        ListNode mHead=null;
        ListNode c=null;
        if(list1==null){
            return list2;
        }
        if(list2==null){
            return list1;
        }
        
        while(list1!=null && list2!=null){
            if(list1.val<=list2.val){
                if(mHead==null){
                    mHead=c=list1;
                }else{
                    c.next=list1;
                    c=c.next;
                }
                list1=list1.next;
            }else{
                if(mHead==null){
                    mHead=c=list2;
                }else{
                    c.next=list2;
                    c=c.next;
                }
                list2=list2.next;
            }
        }
        if(list1==null){
            c.next=list2;
        }else{
            c.next=list1;
        }
        return mHead;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章