zoukankan      html  css  js  c++  java
  • [LeetCode] 21. 合并两个有序链表

    一开始写的没有注意到在while中判断的时候需要判断 l1 和 l2 同时不能为空,否则会一直在循环里,且由于某一个链表走到最后以后再取值会报错,初始链表应该用new ListNode(0)来初始化

    package leetcode;
    
    /**
     * @author doyinana
     * @create 2020-05-01 13:01
     */
    public class L21 {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode head1=l1;
            ListNode head2=l2;
            ListNode head=null;
            ListNode cur=head;
            while(l1!=null||l2!=null){
                if(l1.val<=l2.val){
                    cur.next=l1;
                    l1=l1.next;
                    cur=cur.next;
                }else{
                    cur.next=l2;
                    l2=l2.next;
                    cur=cur.next;
                }
            }
    
            while (l1!=null){
                cur.next=l1;
                cur=cur.next;
                l1=l1.next;
            }
    
            while (l2!=null){
                cur.next=l2;
                cur=cur.next;
                l2=l2.next;
            }
            return head;
        }
    }
    View Code

    正确的写法如下:

    迭代解法

    package leetcode;
    
    /**
     * @author doyinana
     * @create 2020-05-01 13:01
     */
    public class L21 {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
                ListNode dummyHead = new ListNode(0);
                ListNode tail = dummyHead;
                while (l1 != null && l2 != null) {
                    if (l1.val < l2.val) {
                        tail.next = l1;
                        l1 = l1.next;
                    } else {
                        tail.next = l2;
                        l2 = l2.next;
                    }
                    tail = tail.next;
                }
    
                tail.next = l1 == null? l2: l1;
    
                return dummyHead.next;
        }
    }

     递归解法

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if (l1 == null) {
                return l2;
            }
            if (l2 == null) {
                return l1;
            }
            if (l1.val <= l2.val) {
                l1.next = mergeTwoLists(l1.next, l2);
                return l1;
            }
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }

  • 相关阅读:
    C++实现希尔排序和快排
    操作系统重点知识汇总
    结构体(对齐规则及举例)
    指针和引用(传指针和传引用)
    数组和指针
    判断一个字符是否为数字的两种方法(C/C++)
    浅谈操作系统栈和堆(区别与联系)
    浅谈malloc/free和new/delete 的区别
    操作符和表达式
    windows重装系统后grub引导菜单修复方法(亲自实验过)
  • 原文地址:https://www.cnblogs.com/doyi111/p/12813268.html
Copyright © 2011-2022 走看看