以第一个链表为基础,将第二个链表的节点插在合适的位置,但两个链表的地位不是平等的,在末尾的时候需要特殊处理。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
#include <stdlib.h>
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
// write code here
struct ListNode* new_head1 = (struct ListNode*)malloc(sizeof(struct ListNode*));
new_head1->next = pHead1;
new_head1->val = 0;
struct ListNode* new_head2 = (struct ListNode*)malloc(sizeof(struct ListNode*));
new_head2->next = pHead1;
new_head2->val = 0;
struct ListNode* cur1 = pHead1;
struct ListNode* cur2 = pHead2;
struct ListNode* pre1 = new_head1;
struct ListNode* pre2 = new_head2;
while(cur1!= NULL || cur2!= NULL)
{
if(cur1== NULL)
{
pre1->next = cur2;
return new_head1->next;
}
if(cur2==NULL)
{
return new_head1->next;
}
if(cur1->val > cur2->val)
{
pre1->next = cur2;
pre2->next = cur2->next;
cur2->next = cur1;
cur2 = pre2->next;
pre1 = pre1->next;
}
else
{
cur1 = cur1->next;
pre1 = pre1->next;
}
}
return new_head1->next;
}

京公网安备 11010502036488号