题目链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/
题目如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head =new ListNode(0);//为头节点,返回的是头节点的下一个节点
ListNode cur=head;//cur为当前节点
while(l1!=null&&l2!=null){
if(l1.val<l2.val){
cur.next=l1;//相当于head.next=l1;
cur=cur.next;//相当于head=head.next;
l1=l1.next;
}else{
cur.next=l2;
cur=cur.next;
l2=l2.next;
}
}
if(l1==null) cur.next=l2;
else cur.next=l1;
return head.next;
}
}