1.问题描述:将两个排序链表合并为一个新的排序链表。
2.思路:建立一个新的头节点为0的链表,并且建立一个指针让它指向0,再分以下几种情况
①l1或l2为空,则新链表中应插入不空的链表
②若l1,l2都不是空,则新链表中第一个插入的节点应为l1,l2中小的那个
3.代码:
/**
* 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 *p;
ListNode *first=new ListNode(0);
p=first;
while(l1!=NULL||l2!=NULL)
{ if(l1==NULL)
{ p->next=l2;
p=l2;
l2=l2->next;
continue;
}
if(l2==NULL)
{ p->next=l1;
p=l1;
l1=l1->next;
continue;
}
if(l1->val<l2->val)
{ p->next=l1;
p=l1;
l1=l1->next;
}
else {
p->next=l2;
p=l2;
l2=l2->next;
}
}
return first->next;
}
};
4.感想:想问题还是要全面!!!一定别忘记空的情况!!!!