题解 | #相反链表的合并#

相反链表的合并

https://www.nowcoder.com/practice/0222a3c31a404dd3b8c3341d189477f4

先reverse再合并就好了

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param l1 ListNode类 
     * @param l2 ListNode类 
     * @return ListNode类
     */
    ListNode* mergeLists(ListNode* l1, ListNode* l2) {
        l2 = reverseList(l2);
        auto start = new ListNode(-1);
        auto ret = start;
        while(l1!=nullptr&&l2!=nullptr){
            if(l1->val<l2->val){
                start->next = l1;
                l1=l1->next;
                start = start->next;
            }
            else {
                start->next = l2;
                l2=l2->next;
                start = start->next;
            }
        }
        if(l1==nullptr&&l2!=nullptr){
            start->next = l2;
        }
        if(l1!=nullptr&&l2==nullptr){
            start->next = l1;
        }
        return ret->next;
    }
    ListNode* reverseList(ListNode* head){
        if(head==nullptr||head->next==nullptr) return head;
        auto next = head->next;
        head->next = nullptr;
        while(next->next!=nullptr){
            auto tmp = next->next;
            next->next = head;
            head = next;
            next = tmp;
        }
        next->next = head;
        return next;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务