Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

把两个排列好的链表,融合成新的排列好的链表

1、自己的朴素方式

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
     struct ListNode* tmp = malloc(sizeof(struct ListNode));
    struct ListNode* head = tmp;
    struct ListNode* nextP;

    while (l1 != NULL && l2 != NULL)
    {
        nextP = malloc(sizeof(struct ListNode));
        if (l1->val < l2->val)
        {
            nextP->val = l1->val;
            nextP->next = NULL;
            tmp->next = nextP;
            tmp = nextP;
            l1 = l1->next;
            continue;            
//这里有个问题是因为没有使用elseif所以如果不用continue,会继续下面的判断就会出错
        }
        if (l1->val > l2->val)
        {
            nextP->val = l2->val;
            nextP->next = NULL;
            tmp->next = nextP;
            tmp = nextP;
            l2 = l2->next;
            continue;
        }
        if (l1->val == l2->val)
        {
            struct ListNode *twice = malloc(sizeof(struct ListNode));
            twice->val = l1->val;
            twice->next = nextP;
            nextP->val = l1->val;
            nextP->next = NULL;
            tmp->next = twice;
            tmp = nextP;
            l1 = l1->next;
            l2 = l2->next;
            continue;
        }
    }
    if (l1 == NULL)
    {
        tmp->next = l2;
        return head->next;
    }
    if (l2 == NULL)
    {
        tmp->next = l1;
        return head->next;
    }
    return head->next;
}
  • 别人的算法是在中间那一块不需要特别判断一次两个值相等时候
posted @ 2015-09-25 19:48  dylqt  阅读(134)  评论(0编辑  收藏  举报