Leetcode刷题java之21. 合并两个有序链表
解法一:
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution_2 {
public void mergeTwoLists(ListNode n1,ListNode n2) {
ListNode newNode = new ListNode(0);
ListNode cur = newNode;
while(n1!=null && n2!=null) {
if(n1.val < n2.val) {
cur.next = n1;
cur = cur.next;
n1 = n1.next;
}else {
cur.next = n2;
cur = cur.next;
n2 = n2.next;
}
}
//任一为空,直接连接另条表
if(n1 == null) {
cur.next = n2;
}else {
cur.next = n1;
}
cur=newNode.next;
System.out.print("l3: ");
while(cur!=null) {
System.out.print(cur.val);
cur=cur.next;
}
System.out.println();
}
public static void main(String[]args) {
//l1初始化
ListNode l1=new ListNode(1);//新建节点
ListNode pre=l1;//创建头指针