题目:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(NULL == l1) return l2;
if(NULL == l2) return l1;
ListNode *p1 = l1, *p2 = l2;//p1 p2用于遍历l1 l2
ListNode *p = NULL, *head = NULL;//p指向新链表的最后一个节点,head指向新链表的第一个节点
if(p1->val < p2->val){
head = p1;
p1 = p1->next;
}
else{
head = p2;
p2 = p2->next;
}
p = head;
while(p1 && p2){
if(p1->val < p2->val){
p->next = p1;
p1 = p1->next;
}
else{
p->next = p2;
p2 = p2->next;
}
p = p->next;
}
if(p1) p->next = p1;//连接剩余的链表
if(p2) p->next = p2;
return head;
}
};