问题描述:将两个排序链表合并为一个新的排序链表
样例
给出 1->3->8->11->15->null
,2->null
, 返回 1->2->3->8->11->15->null
。
解题思路:遍历第二个链表的每一个节点,然后与第一个节点的第一个节点比较,如果第二个链表节点的值小于第一个,就插入到第一个链表里,如果大于就到下一个节点。然后依次遍历第二个链表的每个节点,便利完成就合成一个新的链表。
实现代码:class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
// write your code here
ListNode *first= new ListNode(0);
first->next=l1;
ListNode *second=l2;
ListNode *dummy=first;
if(first->next==NULL){return l2;}
if(second==NULL){return l1;}
while(first->next!=NULL&&second!=NULL)
{
if(first->next->val <= second->val){
first=first->next;
}
else {
ListNode *temp1=second;
second=second->next;
ListNode *temp2=first->next;
first->next=temp1;
temp1->next=temp2;
}
}
if(second==NULL){
return dummy->next;
}
if(first->next==NULL){
first->next=second;
return dummy->next;
}
}
};
感悟:一开始是有这个思路的,但是代码就是不知道咋写,然后请教了别人,思路感觉很简单,真正上去自己写的时候,感觉就不一样了,以后还得多写。