将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的
1-2-3,2-3-4
1-2-2-3-3-4
步骤:
1、申请一个虚拟结点newHead,data=-1;定义一个temp,newHead=temp
2、定义两个初始变量,headA,headB,条件:都不为空
3、若一个走完,则将剩下的置为temp.next=headB/A
public class Test3 {
public static ListNode mergeTwoLists(ListNode headA, ListNode headB) {
ListNode newHead = new ListNode(-1);
ListNode temp = newHead;
while (headA != null && headB != null) {
if (headA.data < headB.data) {
temp.next = headA;
headA = headA.next;
temp = temp.next;
} else {
temp.next = headB;
headB = headB.next;
temp = temp.next;
}
}
if (headA != null) {
temp.next = headA;
}
if (headB != null) {
temp.next = headB;
}
return newHead.next;
}
结果:
1 3 5 7
2 4 6 8 10
1 2 3 4 5 6 7 8 10