将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head = new ListNode(0);
ListNode* curr = head;
while(l1!=NULL&&l2!=NULL){
if(l1->val<l2->val){
curr->next = l1;
l1 = l1->next;
}else{
curr->next = l2;
l2 = l2->next;
}
curr = curr->next;
}
curr->next = l1==NULL?l2:l1;
return head->next;
}
};
递归做法
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
if(l1->val < l2->val){
l1->next = mergeTwoLists(l1->next,l2);
return l1;
}else{
l2->next = mergeTwoLists(l1,l2->next);
return l2;
}
}
知识
“error: ‘Q’ is a pointer; did you mean to use ‘->’?”
struct Node {
ElementType X;
};
//对于直接传入结构体,使用'.'去访问
void fn(struct Node n)
{
ElementType X = n.X;
}
//对于传入结构体指针,使用'->'去访问
void fn(struct Node *n)
{
ElementType X = n->X;
}