zoukankan      html  css  js  c++  java
  • 合并两个排序的链表

    结点:

    public class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }

    递归方法进行合并:

    public class Solution{
        public ListNode Merge(ListNode list1,ListNode list2){
    
             //检验鲁棒性
             if(list1 == null) return list2; 
             if(list2 == null) return list1; 
    
             //如果list1的第一个元素小,头结点从list1开始;如果list2的第一个元素小,头结点从list2开始
    
             ListNode node = null;
             if(list1.val > list2.val){
                  node = list2;
                  node.next = Merge(list1, list2.next);
             }
             else{
                  node = list1;
                  node.next = Merge(list1.next, list2);
             }
             return node;
        }
    }

    非递归方法进行合并:

    public class Solution{
        public ListNode Merge(ListNode list1,ListNode list2){

             //检验鲁棒性
             if(list1 == null) return list2; 
    if(list2 == null) return list1;

    //如果list1的第一个元素小,头结点从list1开始;如果list2的第一个元素小,头结点从list2开始
    ListNode head
    = null; if(list1.val > list2.val){ head = list2; list2 = list2.next; } else{ head = list1; list1 = list1.next; }
    ListNode node
    = head; while(list1 != null && list2 != null){ if(list1.val > list2.val){ node.next = list2; list2 = list2.next; } else{ node.next = list1; list1 = list1.next; } node = node.next; } if(list1 == null) node.next = list2; if(list2 == null) node.next = list1; return head; } }

    主要思想:

          1) 链表1的头结点值小于链表2的头结点值,则链表1的头结点是合并后链表的头结点;

          2) 在剩余的结点中,链表2的头结点值小于链表1的头结点值,则链表2的头结点是剩余结点的头结点。

          3) 注意代码在鲁棒性方面存在的问题,如空链表时。

  • 相关阅读:
    CopyOnWriteArrayList
    Gradle version 2.2 is required. Current version is 2.10
    install mysql on ubuntu
    A<T extends B> and A <? extends B>
    java event listeners and dispatcher
    git
    linux patch usage
    Codeforces Round #404 (Div. 2) C 二分查找
    dijkstra算法模板及其用法
    Sublime Text 3 快捷键精华版
  • 原文地址:https://www.cnblogs.com/jiqianqian/p/6603922.html
Copyright © 2011-2022 走看看