1. 描述
合并两个有序链表,出自牛客网算法NC33
2. 代码
package com.jfp;
public class Test3 {
/**
*
* @param l1 ListNode类
* @param l2 ListNode类
* @return ListNode类
*/
public static ListNode mergeTwoLists (ListNode l1, ListNode l2) {
ListNode head = new ListNode();
ListNode curr = head;
while (l1 != null || l2 != null){
if(l1 == null){
curr.next = l2;
break;
} else if (l2 == null){
curr.next = l1;
break;
}else if(l1.val < l2.val){
curr.next = l1;
l1 = l1.next;
curr = curr.next;
} else {
curr.next = l2;
l2 = l2.next;
curr = curr.next;
}
}
return head.next;
}
public static class ListNode {
int val;
ListNode next = null;
}
public static void main(String[] args) {
ListNode listNode1 = new ListNode();
listNode1.val=888;
ListNode listNode = mergeTwoLists(null, listNode1);
System.out.println(listNode.val);
}
}
网友评论