[LeetCode]|[LeetCode] 21. Merge Two Sorted Lists

【[LeetCode]|[LeetCode] 21. Merge Two Sorted Lists】这题前几天在哈啰出行南京大学现场笔试碰到了,因为没考虑到“一个链表遍历完,另一个链表没遍历完”这个边界条件,导致笔试挂掉,实在很不应该。亡羊补牢,犹未晚矣,于是我就又在LeetCode上做了一遍。我这里给的Solution可能不是最佳的,但也还凑合。

/** * 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* sentinel = new ListNode(0); ListNode* p = sentinel; while (l1 != nullptr || l2 != nullptr) { if (l1 && !l2) { p->next = new ListNode(l1->val); l1 = l1->next; } else if (!l1 && l2) { p->next = new ListNode(l2->val); l2 = l2->next; } else { if (l1->val < l2->val) { p->next = new ListNode(l1->val); l1 = l1->next; } else { p->next = new ListNode(l2->val); l2 = l2->next; } } p = p->next; } return sentinel->next; } };

    推荐阅读