合并有序链表
题目描述
将两个有序的链表合并为一个新链表,要求新的链表是通过拼接两个链表的节点来生成的,且合并后新链表依然有序。
示例1
输入 {1},{2}
返回值 {1,2}
示例2
输入 {2},{1}
返回值 {1,2}
package 牛客.链表;
/*
*@Author: helen
*@Date: 2021/4/23 9:15
*@Description:
*/
class ListNode {
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
this.next = next;
}
}
public class 合并有序链表 {
public ListNode mergeTwoLists (ListNode l1, ListNode l2) {
// write code here
ListNode head = new ListNode(0);
ListNode cur = head;
while (l1 != null && l2 != null){
if(l1.val < l2.val){
cur.next = l1;
cur = cur.next;
l1 = l1.next;
} else{
cur.next = l2;
cur = cur.next;
l2 = l2.next;
}
}
if(l1 == null){
cur.next = l2;
}
if(l2 == null){
cur.next = l1;
}
return head.next;
}
public static void main(String[] args) {
合并有序链表 obj = new 合并有序链表();
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode L = obj.mergeTwoLists(l1, l2);
while (L != null){
System.out.println(L.val + " ");
L = L.next;
}
}
}