首页 > 其他 > 详细

Merge Two Sorted Lists

时间:2015-09-25 20:25:15      阅读:201      评论:0      收藏:0      [点我收藏+]

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;
}
  • 别人的算法是在中间那一块不需要特别判断一次两个值相等时候

Merge Two Sorted Lists

原文:http://www.cnblogs.com/dylqt/p/4839324.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!