leetcode腾讯精选50-021

    xiaoxiao2022-07-07  198

    题目: https://leetcode-cn.com/problems/merge-two-sorted-lists

    代码: /**

    Definition for singly-linked list.

    struct ListNode {

    int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}

    }; / class Solution { public: ListNode mergeTwoLists(ListNode* l1, ListNode* l2) {

    ListNode *pl1 = l1; ListNode *pl2 = l2;

    ListNode head(0); ListNode *phead = &head;

    while (pl1 != NULL&&pl2 != NULL) { if (pl1->val < pl2->val) { phead->next = pl1; phead = phead->next; pl1 = pl1->next; } else { phead->next = pl2; phead = phead->next; pl2 = pl2->next; }

    }

    if (pl1 == NULL) { phead->next = pl2; }

    if (pl2 == NULL) { phead->next = pl1; }

    return head.next;

    }

    };

    结果:

    最新回复(0)