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) {
ListNode *t1=l1;
ListNode *t2=l2;
ListNode *head=new ListNode(0); //new的应用很巧妙 不用再malloc了
ListNode *temp=head;
while(t1!=NULL||t2!=NULL)
{
while((t2==NULL&&t1!=NULL)||(t1!=NULL&&t1->val<=t2->val))
{
temp->next=t1;
temp=temp->next;
t1=t1->next;
}
while((t1==NULL&&t2!=NULL)||(t2!=NULL&&t1->val>t2->val))
{
temp->next=t2;
temp=temp->next;
t2=t2->next;
}
}
temp->next=NULL;
return head->next;
}
};
1478

被折叠的 条评论
为什么被折叠?



