标签:
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.
Linked List
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
ListNode *ptr1=l1;//l1,l2作为剩下的未放进新链表的各自链表哦当前头结点指针
ListNode *ptr2=l2;//
ListNode *temp;//新链表的尾结点指针
ListNode *root;//最终的头结点
if(l1->val<l2->val)
{
temp=l1;
root=l1;
ptr1=l1->next;
ptr2=l2;
}
else
{
temp=l2;
root=l2;
ptr1=l1;
ptr2=l2->next;
}
while(1)
{
if(ptr2==NULL&&ptr1==NULL)
break;
if(ptr1==NULL&&ptr2!=NULL)
{
temp->next=ptr2;
break;
}
if(ptr1!=NULL&&ptr2==NULL)
{
temp->next=ptr1;
break;
}
if(ptr1->val<ptr2->val)
{
temp->next=ptr1;
ptr1=ptr1->next;
temp=temp->next;
}
else
{
temp->next=ptr2;
ptr2=ptr2->next;
temp=temp->next;
}
}
return root;
}
int main()
{
ListNode *root1=new ListNode(2);
ListNode *root2=new ListNode(1);
ListNode *ptr=mergeTwoLists(root1,root2);
cout<<ptr->val<<‘ ‘<<ptr->next->val<<endl;
}
leetcode_21题——Merge Two Sorted Lists(链表)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4582683.html