链表合成

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

方法一:递归

public class MergeList {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ListNode list1 = new ListNode();
        ListNode list2 = new ListNode();
        ListNode second1=new ListNode();
        ListNode second2=new ListNode();
        ListNode third2=new ListNode();
        list1.nextNode=second1;
        list2.nextNode=second2;
        second2.nextNode=third2;
        list1.data=1;
        second1.data=3;
        list2.data=2;
        second2.data=2;
        third2.data=2;
        MergeList p = new MergeList();
        System.out.println(p.Merge2(list1, list2));
    }
    public ListNode Merge(ListNode list1,ListNode list2) {
           ListNode list= null;//定义一个合完之后的list,初始化为空,也可以是ListNode list=new ListNode();
           /*
            * public class ListNode {
                int val;
                ListNode next = null;
            
                ListNode(int val) {
                    this.val = val;
                }
}*/        if(list1==null) return list2;
           else if(list2==null) return list1;
           if(list1.data<list2.data){
               list=list1;
               list.nextNode=Merge(list1.nextNode,list2);
           }
           else{
               list=list2;
               list.nextNode=Merge(list2.nextNode,list1);
           }
           return list;
     }
}

方法二:非递归

public ListNode Merge2(ListNode list1,ListNode list2) {//非递归的方法
         ListNode list= null;//保存最后合成的链表
         ListNode current=null;//移动节点
         if(list1==null) return list2;
         else if(list2==null) return list1;
         while(list1!=null && list2!=null){//同时不为空的时候才可以比较
            if(list1.data<=list2.data){
                if(list==null)//先判断开始的时候链表是否为空,为空的时候直接赋值
                    current=list=list1;
                else{
                    current.nextNode=list1;
                    current=current.nextNode;//当前节点往后移动
                }
                list1=list1.nextNode;//比较的节点往后移动
            }
            else{
                if(list==null)
                    current=list=list2;
                else{
                    current.nextNode=list2;
                    current=current.nextNode;
                }
                list2=list2.nextNode;
            }
        }
        if(list1==null){//最后在比较完成之后判断链表是否到达结尾,将较长的链表的后面部分直接插入到list中
            current.nextNode=list2;
        }
        if(list2==null){
            current.nextNode=list1;
        }
        return list;
    }
原文地址:https://www.cnblogs.com/tjuxqcui/p/5545188.html