剑指Offer(四)

题目十六:合并两个排序的链表

题目描述:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

解题思路:
递归版本

    public ListNode Merge(ListNode list1,ListNode list2) {

        if (list1 == null) {
            return list2;
        }

        if (list2 == null) {
            return list1;
        }

        if(list1.val <= list2.val){
            list1.next = Merge(list1.next, list2);
            return list1;
        }else{
            list2.next = Merge(list1, list2.next);
            return list2;
        }
    }

非递归版本

     public ListNode Merge(ListNode list1,ListNode list2) {

        if (list1 == null) {
            return list2;
        }

        if (list2 == null) {
            return list1;
        }

        ListNode mergeHead = null;
        ListNode current = null;

        while (list1 != null && list2 != null) {

            if (list1.val <= list2.val) {

                if (mergeHead == null) {
                    mergeHead = current = list1;
                } else {
                    current.next = list1;
                    current = current.next;
                }
                list1 = list1.next;

            } else {

                if (mergeHead == null) {
                    mergeHead = current = list2;
                } else {
                    current.next = list2;
                    current = current.next;
                }
                list2 = list2.next;

            }

        }

        if (list1 == null) {
            current.next = list2;
        } else if (list2 == null) {
            current.next = list1;
        }

        return mergeHead;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 剑指offer(四) 面试题四十:数组中只出现1次的数字 题目:一个整形数组里除了两个数字之外,其他的数字都出现了...
    桥寻阅读 377评论 0 0
  • 剑指Offer笔试题(1) 题目来源:牛客网 题目一 调整数组序列使奇数位于偶数序列前 描述: 输入一个整数数组...
    Torang阅读 1,452评论 0 6
  • 刷题啦刷题啦,剑指offer好像比较有名,所以就在牛客网上刷这个吧~btw,刷了一些题发现编程之美的题好典型啊!!...
    Cracks_Yi阅读 443评论 0 1
  • 说明: 本文中出现的所有算法题皆来自牛客网-剑指Offer在线编程题,在此只是作为转载和记录,用于本人学习使用,不...
    秋意思寒阅读 1,173评论 1 1
  • 剑指offer 最近在牛客网上刷剑指offer的题目,现将题目和答案(均测试通过)总结如下: 二维数组的查找 替换...
    闫阿佳阅读 963评论 0 10