LeetCode_Merge Two Sorted Lists
1. Question Merge Two Sorted ListsTotal Accepted: 63974 Total Submissions: 196044My Submissions
Merge two sorted linked lists and return it as a new list. The new list shoshould be made by splicing together the nodes of the first two lists.
Show Tags Have you met this question in a real interview? Yes No
Discuss
Ii. problem-solving skillsThis is to compare the elements of two sorted lists. When the elements of a list are small, they are added to the output list, and point the pointer to the next element of the list. This question is relatively simple, but there is a boundary condition that two lists may be empty. If l1 is empty, l2 can be returned directly; if l2 is null, l1 can be returned directly, which reduces a lot of computing workload.
Iii. Implementation Code
#include
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/struct ListNode{ int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}};class Solution{public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (!l1) { return l2; } if (!l2) { return l1; } ListNode Head(0); ListNode *Pre = &Head; while(l1 && l2) { if (l1->val < l2->val) { Pre->next = l1; l1 = l1->next; Pre = Pre->next; } else { Pre->next = l2; l2 = l2->next; Pre = Pre->next; } } while (l1) { Pre->next = l1; l1 = l1->next; Pre = Pre->next; } while(l2) { Pre->next = l2; l2 = l2->next; Pre = Pre->next; } return Head.next; }};
Iv. ExperienceThis question mainly deals with the boundary condition. It mainly deals with the case that the linked list is empty, that is, if l1 is empty, l2 is returned. If l2 is empty, l1 is returned directly. A simple question should be fully considered.