File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
21-merge-two-sorted-lists Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ /* *
2+ * Definition for singly-linked list.
3+ * struct ListNode {
4+ * int val;
5+ * ListNode *next;
6+ * ListNode() : val(0), next(nullptr) {}
7+ * ListNode(int x) : val(x), next(nullptr) {}
8+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
9+ * };
10+ */
11+ class Solution {
12+ public:
13+ ListNode* mergeTwoLists (ListNode* list1, ListNode* list2) {
14+ ListNode* dummy = new ListNode (0 );
15+ ListNode* curr = dummy;
16+
17+ // curr l11 l12 ....
18+ // curr -> l11
19+ // ^ ^
20+ while (list1 != NULL and list2 != NULL ) {
21+ if (list1->val <= list2->val ) {
22+ curr->next = list1;
23+ list1 = list1->next ;
24+ } else {
25+ curr->next = list2;
26+ list2 = list2->next ;
27+ }
28+ curr = curr->next ;
29+ }
30+
31+ // curr
32+ // n n n
33+ if (list1 != NULL )
34+ curr->next = list1;
35+
36+ if (list2 != NULL )
37+ curr->next = list2;
38+
39+ return dummy->next ;
40+ }
41+ };
You can’t perform that action at this time.
0 commit comments