题目为给定两个有序的链表,然后将这两个链表合成一个,思想很简单,重新建立一个节点,两个指针分别指向这两个链表,然后按照顺序两个链表进行比较,哪一个小,则节点结哪一个。
解题思路:首先选择新链表的起始点,然后将其进行比较。
代码如下:
#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 * curNode = NULL;
ListNode * head = NULL;
if (head==NULL)
{
if (l1->val<l2->val)
{
head = curNode = l1;
l1 = l1->next;
//curNode->next = NULL;
}
else
{
head = curNode = l2;
l2 = l2->next;
//curNode->next = NULL;
}
}
while (l1&&l2)
{
if (l1->val < l2->val)
{
curNode->next = l1;
curNode = l1;
l1 = l1->next;
curNode->next = NULL;
}
else
{
curNode->next = l2;
curNode = l2;
l2 = l2->next;
curNode->next = NULL;
}
}
if (l1)
{
curNode->next = l1;
}
else
{
curNode->next = l2;
}
return head;
}
在网上看到有人用递归来解决这个问题,之前一直没想到可以用递归,现在将递归的代码贴出来供以后学习用:
递归代码如下:
ListNode* mergeTwoLists1(ListNode* l1, ListNode* l2)
{
if (l1=NULL)
{
return l2;
}
else
{
return l2;
}
ListNode * node = NULL;
if (l1->val<l2->val)
{
node = l1;
mergeTwoLists1(l1->next, l2);
}
else
{
node = l2;
mergeTwoLists1(l1, l2->next);
}
return node;
}