Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 21. Merge Two Sorted Lists #5

Open
Animenzzzz opened this issue Jul 14, 2019 · 0 comments
Open

[LeetCode] 21. Merge Two Sorted Lists #5

Animenzzzz opened this issue Jul 14, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

Description

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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

解题思路:这题和 23题:合并K个链表类似,是其子处理,注意细节就好

C解法:

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    
    struct ListNode *current = NULL;
    struct ListNode *head = current;
    if (l1 == l2) {
        return l1;
    }
    while (l1 && l2)
    {
        if (!head)
        {
            head = (struct ListNode *)malloc(sizeof(struct ListNode));
            head->next = NULL;
            current = head;
        }
        struct ListNode *tmp = (struct ListNode *)malloc(sizeof(struct ListNode));
        tmp->next = NULL;
        if (l1->val < l2->val)
        {
            tmp->val = l1->val;
            current->next = tmp;
            current = current->next;
            l1 = l1->next;
        }else{
            tmp->val = l2->val;
            current->next = tmp;
            current = current->next;
            l2 = l2->next;
        }
    }
    if (!head)
    {
        head = (struct ListNode *)malloc(sizeof(struct ListNode));
        head->next = NULL;
        current = head;
    }
    if(l1) current->next = l1;
    if(l2) current->next = l2;
    return head->next;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant