LeetCode刷题记--第二十一题--C语言

题目:
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

  输入:1->2->4, 1->3->4
  输出:1->1->2->3->4->4

解答:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    //链表第一次赋值的时候记录。
    if(l1 == NULL)
        return l2;
    if(l2 == NULL)
        return l1;
    struct ListNode *p=NULL,*t1=l1,*t2=l2,*head=NULL;
    int temp;
    while(t1!=NULL && t2!=NULL)
    {
        if(t1->val <= t2->val)
        {
            temp = t1->val;
            t1 = t1->next;
        }
        else
        {
            temp = t2->val;
            t2 = t2->next;
        }
        struct ListNode *tl = (struct ListNode *)malloc(sizeof(struct ListNode));
        if(tl==NULL)
            return false;
        tl->next = NULL;
        tl->val = temp;
        if(head == NULL)//注意头节点的处理
        {
            head = tl;
            p=tl;
        }
        else
        {
            p->next = tl;
            p = p->next;
        }
    }
    if(t1!=NULL)
        p->next = t1;
    if(t2!=NULL)
        p->next = t2;
    return head;
}

你可能感兴趣的:(LeetCode刷题)