自己的第一个版本是重新构建了一个新的list,所以用了很多malloc,然后对于这种数据结构的题目,要特别注意判断指针是否指向NULL的情况(末尾),当时就老error,因为总是没考虑到末尾的情况。
malloc新node的AC版本:
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2)
{
if (l1 == NULL && l2 == NULL)
return l1;
struct ListNode *result = NULL;
struct ListNode *node = NULL, *l1p = l1, *l2p = l2, *rp;
int val = 0;
while (l1p != NULL && l2p != NULL) {
if (!result) {
result = (struct ListNode *)malloc(sizeof(struct ListNode));
rp = result;
}
if (l1p->val < l2p->val) {
val = l1p->val;
l1p = l1p->next;
}
else {
val = l2p->val;
l2p = l2p->next;
}
node = (struct ListNode *)malloc(sizeof(struct ListNode));
node->val = val;
rp->next = node;
rp = rp->next;
}
struct ListNode *remainingNodes;
if (l1p) {
if (!result) {
result = (struct ListNode *)malloc(sizeof(struct ListNode));
rp = result;
}
remainingNodes = l1p;
}
else {
if (!result) {
result = (struct ListNode *)malloc(sizeof(struct ListNode));
rp = result;
}
remainingNodes = l2p;
}
while (remainingNodes != NULL) {
node = (struct ListNode *)malloc(sizeof(struct ListNode));
node->val = remainingNodes->val;
rp->next = node;
rp = rp->next;
remainingNodes = remainingNodes->next;
}
rp->next = NULL;
return result->next;
}
第二种是直接修改指针的方法,严蔚敏的书上貌似是这种解法,方便简洁一目了然,而且加了head确实方便很多:
struct ListNode *fixed_mergeTwoLists(struct ListNode *l1, struct ListNode *l2)
{
struct ListNode head = {-1, NULL};
struct ListNode *hp = &head;
while (l1 != NULL && l2!= NULL) {
if (l1->val < l2->val) {
hp->next = l1;
l1 = l1->next;
hp = hp->next;
}
else {
hp->next = l2;
l2 = l2->next;
hp = hp->next;
}
}
if (l1)
hp->next = l1;
else
hp->next = l2;
return head.next;
}