文章目录
题目描述:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
如图:
简单思路:
首先,通过分析题目,我们发现排序最终是要将两个链表合并为一个链表,不妨我们可以先设定一个新的头结点和一个指向这个结点的指针,然后,通过结点和利用链表各自的头结点进行比较等操作。
详细分析:
首先,只要判断两个链表不为空,就可以让比较继续进行,代码如下:
while(list1 != null && list2 != null){
if(list1.val < list2.val){
cur.next = list1;
cur = cur.next;
list1 = list1.next;
}
else{
cur.next = list2;
cur = cur.next;
list2 = list2.next;
}
}
逻辑实现图如下:
1.通过比较发现元素等大,将 List2 地址传给head。
2.将 cur 指向 List2 并让 List2 向后移
3.比较后发现1<3,将 List1 的地址传递给 cur.next。
4.将 cur 指向 List1 的位置
5.List1 位置后移
6.通过比较发现2<3,元素不变cur后移。
7.List1后移。
8.通过比较发现3<4,将cur.next 传入List2现在指向的地址
9.cur指向List2,List2后移
10.发现4 == 4,将 List1 的地址传给 cur
最后cur指到 List1 ,List2后移,List1指向null,循环结束。
整体代码如下:
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode Head = new ListNode();
ListNode cur = Head;
while(list1 != null && list2 != null){
if(list1.val < list2.val){
cur.next = list1;
cur = cur.next;
list1 = list1.next;
}
else{
cur.next = list2;
cur = cur.next;
list2 = list2.next;
}
}
//这里是判断如果出现不等长链表,将多余的直接连接整体后面。
if(list1 == null){
cur.next = list2;
}
if(list2 == null){
cur.next = list1;
}
return Head.next;
}
}