算法内容
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
算法思想
合并两个有序链表,也是在《数据结构与算法》这门课程中接触过的一个算法题。合并两个有序链表的算法同样用图来直观的表述该算法思想。
整体算法
public class Day_19 {
static Scanner input=new Scanner(System.in);
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode listNode_finally=new ListNode(0);
ListNode listNode_mid=listNode_finally;
while (l1!=null&&l2!=null){
if(l1.val>l2.val){
listNode_mid.next=l2;
listNode_mid=l2;
l2=l2.next;
}else{
listNode_mid.next=l1;
listNode_mid=l1;
l1=l1.next;
}
}
if (l1 != null) {
//此处可以直接链接:listNode_mid.next=l1
while (l1!=null){
listNode_mid.next=l1;
listNode_mid=l1;
l1=l1.next;
}
}
if(l2 != null){
while (l2!=null){
listNode_mid.next=l2;
listNode_mid=l2;
l2=l2.next;
}
}
return listNode_finally.next;
}
public static ListNode input_link_test(int n, ListNode head){
ListNode temp=head;
for (int i = 0; i < n-1; i++) {
int num =input.nextInt();
ListNode listNode=new ListNode(num,null);
temp.next=listNode;
temp=temp.next;
}
return head;
}
public static void main(String[] args) {
System.out.print("输入单链表1长度n:");
int n=input.nextInt();
System.out.println("----------------------------------------------------------");
System.out.println("输入测试数字:");
ListNode head=new ListNode();
if(n>0){
int num =input.nextInt();
head=new ListNode(num,null);
input_link_test(n,head);
}else{
head=null;
}
System.out.println("-----------------------------------------------------------");
System.out.print("输入单链表2长度n:");
int n1=input.nextInt();
System.out.println("----------------------------------------------------------");
System.out.println("输入测试数字:");
ListNode head1=new ListNode();
if(n1>0){
int num1 =input.nextInt();
head1=new ListNode(num1,null);
input_link_test(n1,head1);
}else {
head1=null;
}
System.out.println("-----------------------------------------------------------");
ListNode listNode=mergeTwoLists(head1,head);
while (listNode!=null){
System.out.println(listNode.val);
listNode=listNode.next;
}
}
}
尾语
以上属于个人见解,有好的想法可以在下方评论写出自己的想法,大家一起进步。该题是力扣上的题,若有侵权,请及时告知。该题链接:https://leetcode-cn.com/problems/merge-two-sorted-lists