将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
package list;
/**
* @AUTHOR:LKR
* @DATE:2019/3/7
* @DESCRIPTION:合并两个有序链表
* 定义头结点
* 当两个链表都不为空是,比较大小,指针指向小的节点,
* 如果有一个链表为空,直接指向另一个不为空链表
**/
public class SortTwoLinkedList {
public static ListNode solution(ListNode l1,ListNode l2){
ListNode dummyHead = new ListNode(0);
ListNode cur = dummyHead;
while(l1 != null &&l2 != null){
if(l1.data < l2.data){
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 dummyHead.next;
}
//打印链表
private static void print(ListNode node) {
System.out.print(node.data +" ");
if (node.next != null){
print(node.next);
}
}
public static void main(String[] args){
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
ListNode node6 = new ListNode(6);
ListNode node7 = new ListNode(7);
ListNode node8 = new ListNode(8);
ListNode node9 = new ListNode(9);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
node6.next = node7;
node7.next = node8;
node8.next = node9;
ListNode list1 = new ListNode(1);
ListNode list2 = new ListNode(1);
ListNode list3 = new ListNode(3);
ListNode list4 = new ListNode(33);
ListNode list5 = new ListNode(45);
ListNode list6 = new ListNode(65);
ListNode list7 = new ListNode(75);
ListNode list8 = new ListNode(82);
ListNode list9 = new ListNode(91);
list1.next = list2;
list2.next = list3;
list3.next = list4;
list4.next = list5;
list5.next = list6;
list6.next = list7;
list7.next = list8;
list8.next = list9;
print(node1);
print(list1);
System.out.println(" 合并后链表");
print(solution(node1,list1));
}
}
输出结果
1 2 3 4 5 6 7 8 9 1 1 3 33 45 65 75 82 91
合并后链表
1 1 1 2 3 3 4 5 6 7 8 9 33 45 65 75 82 91
Process finished with exit code 0