题解 | #链表合并#
链表合并
http://www.nowcoder.com/practice/46bda7f0570a47b6b54a29a0a6ae4c27
java递归写法
- 思路参考leetcode
- https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/yi-kan-jiu-hui-yi-xie-jiu-fei-xiang-jie-di-gui-by-/
import java.util.*;
//定义链表
class ListNode{
int val;
ListNode next;
ListNode(){};
ListNode(int val){
this.val=val;
}
ListNode(int val,ListNode next){
this.val=val;
this.next=next;
}
}
public class Main{
//定义main函数
public static void main(String[] args){
Scanner sc =new Scanner(System.in);
ListNode list1=createList(sc.nextLine().split(" "));
ListNode list2=createList(sc.nextLine().split(" "));
ListNode list=combineList(list1,list2);
//输出
while(list!=null){
System.out.print(list.val+" ");
list=list.next;
}
}
//创建链表
public static ListNode createList(String [] str){
//边界条件
if(str==null||str.length==0){
return null;
}
//建立节点
ListNode pre=new ListNode(0);
//预留头节点,用以return
ListNode list=pre;
//循环读取相应文本转换为数字放入listz中
for(int i=0;i<str.length;i++){
list.next=new ListNode(Integer.parseInt(str[i]));
list=list.next;
}
//返回头节点
return pre.next;
}
//
public static ListNode combineList(ListNode l1,ListNode l2){
//边界条件
if(l1==null) return l2;
else if(l2==null) return l1;
//进行递归
else if(l1.val<l2.val){
l1.next=combineList(l1.next,l2);
return l1;
}
else{
l2.next=combineList(l2.next,l1);
return l2;
}
}
}