zoukankan      html  css  js  c++  java
  • java:合并两个排序的链表(递归+非递归)

    //采用不带头结点的链表  非递归实现
    public static ListNode merge(ListNode list1,ListNode list2){
    	if(list1==null)
    		return list2;
    	else if(list2==null)
    		return list1;
    	
    	ListNode newHead=null;
    	ListNode tmp=null;
    	//往新链表一个个添加节点 直至有一个链表为空
    	//tmp存放最后一个添加进新链表的节点 用于后续的拼接
    	while(list1!=null&&list2!=null){
    		if(list1.value<list2.value){
    			if(newHead==null){
    				newHead=tmp=list1;
    			}else{
    				tmp.next=list1;
    				tmp=tmp.next;
    			}
    			list1=list1.next;
    		}else{
    			if(newHead==null){
    				newHead=tmp=list2;
    			}else{
    				tmp.next=list2;
    				tmp=tmp.next;
    			}
    			list2=list2.next;
    		}
    	}
    	//拼接剩余链表至新链表尾节点
    	if(list1==null){
    		tmp.next=list2;
    	}else{
    		tmp.next=list1;
    	}
    	return newHead;	
    }
    
    //递归实现
    public static ListNode mergeRecur(ListNode list1,ListNode list2){
    	if(list1==null)
    		return list2;
    	if(list2==null)
    		return list1;
    	
    	ListNode newHead=null;
    	if(list1.value<=list2.value){
    		newHead=list1;
    		newHead.next=mergeRecur(list1.next, list2);
    	}else{
    		newHead=list2;
    		newHead.next=mergeRecur(list1, list2.next);
    	}
    	return newHead;
    }
    

      

  • 相关阅读:
    canvas实现文字分行
    二维码扫描添加闪光灯的功能
    修改二维码扫描框的大小位置
    Android中实现EditText圆角的方法
    利用FrameLayout实现遮罩层
    EditText中的灰色提示
    实现等待动画
    发送短信
    自定义EditText动态在EditText中添加图片
    xml解析
  • 原文地址:https://www.cnblogs.com/czsblog/p/10695897.html
Copyright © 2011-2022 走看看