描述
合并两个有序的单链表,使合并之后的结果仍然有序
样例
给出 1->3->8->11->15->null,2->null
返回 1->2->3->8->11->15->null
代码
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
// write your code here
ListNode* p1=l1;
ListNode* p2=l2;
ListNode* n=NULL;
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
//找出新链表的头节点
if(p1->val<p2->val)
{
n=p1;
p1=p1->next;
}
else
{
n=p2;
p2=p2->next;
}
ListNode* newlist=n;
//将p1和p2中的节点有序的插入新链表
while(p1 && p2)
{
if(p1->val<p2->val)
{
n->next=p1;
p1=p1->next;
n=n->next;
}
else
{
n->next=p2;
p2=p2->next;
n=n->next;
}
}
//将p1或者p2中剩余的节点插入新链表
while(p1)
{
n->next=p1;
p1=p1->next;
n=n->next;
}
while(p2)
{
n->next=p2;
p2=p2->next;
n=n->next;
}
return newlist;
}
};