一.问题描叙:有两个链表L1,L2,都是有序的,先要求将这个链表合并,合并后的链表依然要求是有序的。
二.问题解释:如下图。
链表L1:
链表L2:
合并后的链表:
三.方法图解
步骤1:比较L1和L2指向的节点,将较小的节点放在临时头节点后面
比较并添加后临时头节点temp_head, L1,L2的变化
步骤2:循环上面的步骤,直到将某一个链表遍历完。
四.完整代码:
#include<iostream>
using namespace std;
struct ListNode
{
int data;
ListNode *next;
ListNode(int x):data(x),next(NULL){}
};
class Solution
{
public:
ListNode* mergeTwoLists(ListNode *L1,ListNode* L2)
{
ListNode temp_head(0);
ListNode* pre=&temp_head;
while(L1&&L2)
{
if(L1->data<L2->data)
{
pre->next=L1;
L1=L1->next;
}
else
{
pre->next=L2;
L2=L2->next;
}
pre=pre->next;
}
if(L1)
{
pre->next=L1;
}
if(L2)
{
pre->next=L2;
}
return temp_head.next;
}
};
int main()
{
//定义每个节点并初始化
ListNode a(1);
ListNode b(4);
ListNode c(6);
ListNode d(0);
ListNode e(5);
ListNode f(7);
//将每个节点连接起来
a.next=&b;
b.next=&c;
d.next=&e;
e.next=&f;
Solution solve;
ListNode *head=solve.mergeTwoLists(&a,&d);//对两个链表进行合并处理
cout<<"After merge:"<<endl;
while(head)//循环输出合并后的链表元素
{
cout<<head->data;
head=head->next;
}
return 0;
}