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;
        }
    }

  • 相关阅读:
    【Redis】事务
    【Web】Apache HttpClient & HttpAsyncClient
    【Spring】导入配置文件
    【SpringBoot】@Conditional注解家族
    【前端开发】dva+antd+react
    【Spring】EnableXXX
    POJ-2240-Arbitrage
    POJ-2387-Til the Cows Come Home
    hdu-1847-畅桶工程续
    Floyd算法模板(多源最短)
  • 原文地址:https://www.cnblogs.com/doyi111/p/12813268.html
Copyright © 2011-2022 走看看