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.
Subscribe to see which companies asked this question
思路:
新建一个链表,然后比较两个链表中的元素值,把较小的那个链到新链表中,然后较小链表与另一个链表的额值继续进行比较,跟合并数组差不多,由于两个输入链表的长度可能不同,所以最终会有一个链表先完成插入所有元素,则直接另一个未完成的链表直接链入新链表的末尾。
/**
* 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* newnode=new ListNode(NULL);
ListNode* head=newnode;//保存头结点
while(l1!=NULL && l2!=NULL)
{
if(l1->val<l2->val)
{
newnode->next=l1;
l1=l1->next;//进行l1链表的 下一个节点与l2比较
}
else
{
newnode->next=l2;
l2=l2->next;
}
newnode=newnode->next;//保持最前方的节点
}
if(l1==NULL) newnode->next=l2;
if(l2==NULL) newnode->next=l1;
return head->next; //因为头结点是有元素的,所以链表的头结点是head->next
}
};