标签:int list while amp code 有序链表 lse 通过 else
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
/** * 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) { if(l1 == nullptr && l2 == nullptr){ return l1; } if(l1 == nullptr && l2 != nullptr){ return l2; } if(l1 != nullptr && l2 == nullptr){ return l1; } ListNode *head = nullptr; ListNode *tail = nullptr; if(l1->val <= l2->val){ head = l1; tail = l1; l1 = l1->next; } else{ head = l2; tail = l2; l2 = l2->next; } while(!(l1 == nullptr || l2 == nullptr)){ if(l1->val <= l2->val){ tail->next = l1; l1 = l1->next; } else{ tail->next = l2; l2 = l2->next; } tail = tail->next; } if(l1 == nullptr){ tail->next = l2; } if(l2 == nullptr){ tail->next = l1; } return head; } };
标签:int list while amp code 有序链表 lse 通过 else
原文地址:https://www.cnblogs.com/olajennings/p/12466889.html