题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
//定义两个指针指向两个链表比较大小,谁小加入谁
ListNode cur1 = list1;
ListNode cur2 = list2;
//定义新链表的头节点
ListNode head = new ListNode(0);
ListNode cur = head;
while(cur1!=null&&cur2!=null){
if(cur1.val<cur2.val){
cur.next = cur1;
cur1 = cur1.next;
cur = cur.next;
}else{
cur.next = cur2;
cur2 = cur2.next;
cur = cur.next;
}
}
if(cur1==null){
cur.next = cur2;
}else{
cur.next = cur1;
}
return head.next;
}
}