题目:合并两个有序链表,将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
合并两个有序链表
1.分析
- 首先定义一个傀儡结点
newHead
,让中间结点tmp
指向它,两个链表头结点headA
和headB
- 当两个表都不为空就进入循环
- 首先就将表
headA.val
和headB.val
进行比较,谁小谁就放在newHead
的后面,然后头结点后移,tmp
后移 - 循环走完,当两个表有一个为空时,谁不为空,
tmp.next
就等于谁
2.具体步骤
3.代码实现
public static ListNode mergeTwoLists(ListNode headA, ListNode headB) {
ListNode newHead = new ListNode(-1);
ListNode tmp = newHead;
while (headA != null && headB != null) {
if (headA.val < headB.val) {
tmp.next = headA;
headA = headA.next;
tmp = tmp.next;
} else {
tmp.next = headB;
headB = headB.next;
tmp = tmp.next;
}
}
if (headA != null) {
tmp.next = headA;
}
if (headB != null) {
tmp.next = headB;
}
return newHead.next;
}
测试:
public static void main(String[] args) {
MyLinkedList myLinkedList1 = new MyLinkedList();
myLinkedList1.addLast(12);
myLinkedList1.addLast(23);
myLinkedList1.addLast(34);
myLinkedList1.addLast(45);
myLinkedList1.addLast(56);
System.out.println(" myLinkedList1:");
myLinkedList1.display();
MyLinkedList myLinkedList2 = new MyLinkedList();
myLinkedList2.addLast(13);
myLinkedList2.addLast(24);
myLinkedList2.addLast(30);
System.out.println(" myLinkedList2:");
myLinkedList2.display();
ListNode ret=mergeTwoLists(myLinkedList1.head,myLinkedList2.head);
System.out.println("拼接后:");
myLinkedList1.display2(ret);
}