输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
想法☁:
1.题目告诉两个链表,那你首先应想到,如果给你的两个链表的其中一个是空的,则返回另外一个链表节点头就好了。
2.新定义一个链表的头节点,该结点就是要返回的结点哦。
3.定义三个指针,用来跑链表。
4.如果整个循环跳出,则表示其中一个链表为空,则把新链表尾节点的next域设置为不为空链表的指针就?了。
/*
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null)
return list2;
if(list2 == null)
return list1;
//跑list1的指针
ListNode p = list1;
//跑list2的指针
ListNode q = list2;
//确定新链表的头结点
ListNode newList = (p.val < q.val)? p : q;
//跑新链表的指针
ListNode s = newList;
if(newList == q)
q = q.next;
else
p = p.next;
while(p != null && q != null){
if(p.val < q.val){
s.next = p;
s = p;
p = p.next;
}else{
s.next = q;
s = q;
q = q.next;
}
}
//把不为空的 p/q 直接挂在 s.next 上
if(p != null)
s.next = p;
else
s.next = q;
return newList;
}
}
递归思想⭕
每次合并之前都要比较两个链表的头节点值的大小,故能通过递归去做这个题。
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null)
return list2;
if(list2 == null)
return list1;
ListNode newHead = null;
if(list1.val < list2.val){
newHead = list1;
//看清楚递归进去是确定 newHead.next 的值!!!
newHead.next = Merge(list1.next,list2);
}else{
newHead = list2;
newHead.next = Merge(list1,list2.next);
}
return newHead;
}
}