牛客链接
合并两个排序的链表
题目
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解题思路
先比较list1和list2的头结点大小,先记录下来,这就是要返回的头结点。
然后根据list1和list2各个节点的大小比较,谁小就让当前节点cur的next指向哪个节点,然后让cur向后移动继续去寻找下一个节点,循环结束即可。
代码实现
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null) return list2;
if(list2 == null) return list1;
ListNode newHead = null;
ListNode cur = null;
if(list1.val <= list2.val){
cur = newHead = list1;
list1 = list1.next;
}else{
cur = newHead = list2;
list2 = list2.next;
}
while(list1 != null && list2!=null) {
if(list1.val<=list2.val) {
cur.next = list1;
list1 = list1.next;
}else{
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
if(list1 == null) {
cur.next = list2;
}else{
cur.next = list1;
}
return newHead;
}
}