题目:合并两个有序链表
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
链表操作,新增一个表头,头结点next指针指 l1的表头,依次比 l1 的节点,和 l2 节点的大小,若 l1 较小,l1指向下一个,l2不动接着比较,若l2较小,将节点插入l1节点前面,l2指向下一个,如此反复,直至有一个链表结束,l1先结束,将l2剩余节点挂在l1尾部,若l2结束,则不用处理。最后返回新增表头的后一个节点
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* Head = new ListNode(0,l1);
ListNode* prev = Head;
ListNode* p1 = l1,*p2 = l2;
while(p1 && p2)
{
if(p2->val < p1->val){
ListNode* tmp = p2;
p2 = p2->next;
tmp->next = p1;
prev->next = tmp;
prev = prev->next;
}
else
{
prev = p1;
p1 = p1->next;
}
}
if(!p1)
prev->next = p2;
return Head->next;
}
};