首页 > 试题广场 >

给出两个分别有序的单链表,将其合并成一条新的有序单链表。

[问答题]
给出两个分别有序的单链表,将其合并成一条新的有序单链表。
直接对两个链表进行归并即可。
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null) return list2;
        if(list2 == null) return list1;
        ListNode dummy = new ListNode(0);
        ListNode newhead = dummy;
        while(list1 != null && list2 != null){
            if(list1.val < list2.val){
                dummy.next = list1;
                list1 = list1.next;
            }else{
                dummy.next = list2;
                list2 = list2.next;
            }
            dummy = dummy.next;
        }
        if(list1 != null) dummy.next = list1;
        if(list2 != null) dummy.next = list2;
        return newhead.next;
    }
}


发表于 2020-10-24 13:35:51 回复(0)
// // Created by oujie on 2019-08-05. // #include <iostream> using namespace std; struct ListNode{ int val; ListNode* next;
    ListNode(int x): val(x),next(NULL){}
}; class Solution{ public: ListNode* order2(ListNode* l1,ListNode* l2){ if(l2==nullptr) return l1; if(l1==nullptr) return l2; ListNode* head; if(l1->val<=l2->val){
            head=l1;
            l1=l1->next;
        }else{
            head=l2;
            l2=l2->next;
        }
        head->next=order2(l1,l2); return head;
    }
}; int main(){ ListNode* l1=new ListNode(1);
    l1->next=new ListNode(3);
    l1->next->next=new ListNode(5); ListNode *l2=new ListNode(2);
    l2->next=new ListNode(3);
    l2->next->next=new ListNode(7); Solution s; ListNode* p=s.order2(l1,l2); while(p){
        cout<<p->val<<" ";
        p=p->next;
    }
}
发表于 2019-08-05 13:35:31 回复(0)