Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Subscribe to see which companies asked this question.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null) return l2;
if(l2==null) return l1;
ListNode cur=new ListNode(0);//移动的指针
ListNode head=cur;//链表头 保持不动
while(l1!=null||l2!=null){
if(l1!=null&&l2!=null){
if(l1.val>=l2.val){
cur.next = new ListNode(l2.val);
l2=l2.next;
}else{
cur.next = new ListNode(l1.val);
l1=l1.next;
}
cur = cur.next;
}else if(l1==null){
cur.next = new ListNode(l2.val);
l2=l2.next;
cur = cur.next;
}
else{
cur.next = new ListNode(l1.val);
l1=l1.next;
cur = cur.next;
}
}
return head.next;
}
}
一般我们会用一个cur指向开头 并且用于移动
再用一个head储存头指针 用于返回
while的循环是,每次if一个个执行,执行完之后再到外面判断,判断完再执行下一轮