代码拉取完成,页面将自动刷新
package pers.vic.basics.leetcode;
/**
* @author Vic.xu
* @description: 21. 合并两个有序链表
* @date: 2020/11/11 0011 11:36
*/
public class J0021_E_MergeTwoLists {
/*
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
*/
/**
* 递归遍历
*/
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2==null){
return l1;
}
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
}else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
//暴力遍历 反正是有序的
public static ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
//暴力遍历:有序的
ListNode dummy = new ListNode();
ListNode pref = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
pref.next = l1;
l1 = l1.next;
} else {
pref.next = l2;
l2 = l2.next;
}
pref = pref.next;
}
if (l1 != null) {
pref.next = l1;
} else if (l2 != null) {
pref.next = l2;
}
return dummy.next;
}
/*
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
*/
public static void main(String[] args) {
//1->2->4
ListNode n1 = new ListNode(4);
ListNode n2 = new ListNode(2, n1);
ListNode l1 = new ListNode(1, n2);
// 1->3->4
ListNode n3 = new ListNode(4);
ListNode n4 = new ListNode(3, n3);
ListNode l2 = new ListNode(1, n4);
ListNode head = mergeTwoLists(l1, l2);
ListNode node = head;
while (node != null) {
System.out.println(node.val + "→");
node = node.next;
}
}
}
// Definition for singly-linked list.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。