牛客题霸NC33题解
合并有序链表
https://www.nowcoder.com/practice/a479a3f0c4554867b35356e0d57cf03d?tpId=117&&tqId=34954&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking
合并有序链表
牛客题霸NC33
难度:Easy
题目描述
将两个有序的链表合并为一个新链表,要求新的链表是通过拼接两个链表的节点来生成的。
输入
{1},{}
返回值
{1}
输入
{1},{1}
返回值
{1,1}
代码解决
算法入门基础题,尾插法扫描拼接即可:
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param l1 ListNode类 * @param l2 ListNode类 * @return ListNode类 */ public ListNode mergeTwoLists (ListNode l1, ListNode l2) { // write code here ListNode head = new ListNode(-1); ListNode tail = head; while(l1 != null || l2 != null){ if(l1 != null && l2 != null){ ListNode cur; if(l1.val < l2.val){ cur = l1; l1 = l1.next; } else{ cur = l2; l2 = l2.next; } tail.next = cur; tail = cur; } else{ tail.next = l1 == null ? l2 : l1; break; } } return head.next; } }