• [LeetCode]80. Merge Two Sorted Lists合并两个排序链表


    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.

    Subscribe to see which companies asked this question

    解法1:递归。首先比较头节点大小,若l2->val>l1->val,则返回mergeTwoLists(l2,l1);否则(1)如果l1->next!=NULL,则比较l1->next->val与l2->val的大小,这样可以确定前两个元素的顺序,

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            if (l1 == NULL) return l2;
            if (l2 == NULL) return l1;
            if (l1->val <= l2->val) {
                if (l1->next != NULL && l1->next->val <= l2->val){
                    ListNode* node = mergeTwoLists(l1->next->next, l2);
                    l1->next->next = node;
                }
                else if (l1->next != NULL && l1->next->val > l2->val) {
                    ListNode* node = mergeTwoLists(l1->next, l2->next);
                    l2->next = node;
                    l1->next = l2;
                }
                else
                    l1->next = l2;
                return l1;
            }
            else
                return mergeTwoLists(l2, l1);
        }
    };

    解法2:迭代。新建一个指针help,然后遍历l1和l2,将二者中较小的链接到help后面。最后返回help的下一个节点作为头节点。注意两个链表可能长度不一样,要将长链表最后剩下的元素链接到新链表中。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            if (l1 == NULL) return l2;
            if (l2 == NULL) return l1;
            ListNode* help = new ListNode(0);
            ListNode* head = help;
            while (l1 != NULL && l2 != NULL) {
                if (l1->val <= l2->val) {
                    help->next = l1;
                    l1 = l1->next;
                }
                else {
                    help->next = l2;
                    l2 = l2->next;
                }
                help = help->next;
            }
            if (l1 != NULL) help->next = l1;
            if (l2 != NULL) help->next = l2;
            return head->next;
        }
    };
  • 相关阅读:
    自定义 mapper
    solr 服务搭建
    jedis 连接redis
    jedis 整合 Spring
    Redis 安装
    HttpClient 工具类
    springMvc 中返回字符串 乱码解决
    linux常用命令解析
    压缩jar包
    控制反转
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4964996.html
Copyright © 2020-2023  润新知