牛客题霸 [合并有序链表] C++题解/答案
题目描述
将两个有序的链表合并为一个新链表,要求新的链表是通过拼接两个链表的节点来生成的。
题解:
首先判断l1和l2是否为空
然后依次比较l1和l2的值,然后存到新的链表里,当有一方全部结束时,另一部分剩下的所有直接连在链表后面
代码:
/*** struct ListNode {* int val;* struct ListNode *next;* };*/class Solution {
public:/*** * @param l1 ListNode类 * @param l2 ListNode类 * @return ListNode类*/ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {// write code hereif(l1==NULL&&l2==NULL)return NULL;else if(l2==NULL)return l1;else if(l1==NULL)return l2;ListNode *head = new ListNode(0);ListNode *tail=head;while(l1!=NULL&&l2!=NULL){if(l1->val<=l2->val){tail->next=l1;l1=l1->next;}else {tail->next=l2;l2=l2->next;}tail = tail->next;}if(l1==NULL)tail->next=l2;else tail->next=l1;return head->next;}
};