美文网首页
LeetCode:Merge Two Sorted Lists合

LeetCode:Merge Two Sorted Lists合

作者: 静之先生 | 来源:发表于2015-07-05 23:54 被阅读1018次

    这道题是合并两个有序的链表,返回一个新的有序的链表.题并难度并不大.
    大体思路:使用递归
    步骤:
    1.判断L1,L2是否为空
    2.创建一个头指针
    3.判断当前L1,L2指向的节点值的大小.根据结果,让头指针指向小节点,并让这个节点往下走一步,作为递归函数调用的参数放入,返回的就是新的两个值的比较结果,则新的比较结果放入头结点的下一个节点.
    4.返回头结点

    今天先写到这里,明天试试别的有趣的方法.

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode *head = NULL;
        if(l1 == NULL)
        {
            return l2;
        }
        if(l2 == NULL)
        {
            return l1;
        }
        
        if(l1->val <= l2->val)
        {
            head = l1;
            head->next = mergeTwoLists(l1->next,l2);
        }
        else
        {
            head = l2;
            head->next = mergeTwoLists(l1,l2->next);
        }
        return head;
    }
    

    相关文章

      网友评论

          本文标题:LeetCode:Merge Two Sorted Lists合

          本文链接:https://www.haomeiwen.com/subject/ysuyqttx.html