码迷,mamicode.com
首页 > 其他好文 > 详细

Merge Two Sorted Lists

时间:2015-09-25 20:28:26      阅读:170      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!