AcWing 36. 合并两个排序的链表
原题链接
简单
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2) {
ListNode* L = new ListNode(-1); //意思是调用单链表结构体的构造函数创建了一个头结点为-1的单链表
ListNode* r = L;
ListNode* p = l1, * q = l2; //p指针指向l1,q指针指向l2
while(p && q){
if(p->val <= q->val){
r->next = p;
r = p;
p = p->next;
}else{
r->next = q;
r = q;
q = q->next;
}
}
if(!p) r->next = q;
if(!q) r->next = p;
return L->next; //返回头结点的下一结点,从首元结点开始输出
}
};