剑指OFFER 合并两个排序的链表
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* head = NULL;//'结果链表'的头部
ListNode* cur = NULL;//始终指向'结果链表'的尾部
//添加到head链表中
void push_back(int val)
{
if(head == NULL)
{
head = (ListNode*)malloc(sizeof(ListNode));
head->val = val;
head->next = NULL;
cur = head;
return ;
}
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
cur->next = node;
cur = node;
}
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
head = NULL;
cur = head;//防止OJ不初始化成员变量(手动预防针)
ListNode * p1 = pHead1;
ListNode * p2 = pHead2;
while(p1 != NULL || p2 != NULL)
{
//如果p1到尾了,那么就只拷贝p2
if(p1 == NULL)
{
push_back(p2->val);
p2 = p2->next;
continue;
}
//如果p2到尾了,那么就只拷贝p1
if(p2 == NULL)
{
push_back(p1->val);
p1 = p1->next;
continue;
}
//递增形式进行拷贝
if(p1->val < p2->val)
{
push_back(p1->val);
p1 = p1->next;
}else{
push_back(p2->val);
p2 = p2->next;
}
}
//如果能从while循环中出来,表示p1,p2都为NULL
return head;
}
};