合并两个有序链表
简单题,链表要用草稿纸画出来,不然会把自己绕晕
/**
* 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* list1, ListNode* list2) {
if(list1==NULL)
return list2;
if(list2==NULL)
return list1;
ListNode* shead=new ListNode(0); // 设置一个虚拟头结点;
shead->next=list2;
while(list1)//处理list1中的每一个节点,插入到list2中
{
ListNode* temp=list1;//记录当前节点
list1=list1->next;
ListNode* cur2=shead;
while(cur2->next&&temp->val>cur2->next->val)
{
cur2=cur2->next;
}
temp->next=cur2->next;
cur2->next=temp;
}
return shead->next;
}
};