/*
输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
*/
#include <bits/stdc++.h>
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
//非递归
/* class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
ListNode* pHead = new ListNode(-1);
ListNode* CurNode = pHead;
while (pHead1 && pHead2)
{
if (pHead1->val < pHead2->val)
{
CurNode->next = pHead1;
pHead1 = pHead1->next;
}
else
{
CurNode->next = pHead2;
pHead2 = pHead2->next;
}
CurNode = CurNode->next;
}
CurNode->next = pHead1? CurNode->next = pHead1 : CurNode->next = pHead2;
return pHead->next;
}
}; */
//递归
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
if(pHead1 == nullptr)
return pHead2;
if(pHead2 == nullptr)
return pHead1;
if (pHead1->val < pHead2->val)
{
pHead1->next = Merge(pHead1->next, pHead2);
return pHead1;
}
else
{
pHead2->next = Merge(pHead1, pHead2->next);
return pHead2;
}
}
};
/*
输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
*/
package main
/* type ListNode struct {
Val int
Next *ListNode
} */
/**
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
func Merge(pHead1 *ListNode, pHead2 *ListNode) *ListNode {
pHead := new(ListNode)
curNode := pHead
for pHead1 != nil && pHead2 != nil {
if pHead1.Val < pHead2.Val {
curNode.Next = pHead1
pHead1 = pHead1.Next
}else{
curNode.Next = pHead2
pHead2 = pHead2.Next
}
curNode = curNode.Next
}
if pHead1 != nil{
curNode.Next = pHead1
}
if pHead2 != nil {
curNode.Next = pHead2
}
return pHead.Next
}