通过万岁!!!
- 题目:就是给你两个有序的链表,然后进行合并,要求合并后还是有序的。
- 思路:就是遍历即可,这里面需要一个临时变量(指针)进行过度,他会在两个链表之间来回跳动,并且逐渐往下走。除此之外还需要记录一下头节点。注意,这里我们判断的条件是两个都不为空的时候,只要有一个是空,我们就将剩下的都加到尾部即可。
- 技巧:无,就是遍历一下即可。
java代码
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null) return list2;
if (list2 == null) return list1;
ListNode ans = new ListNode(0);
ListNode temp = ans;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
temp.next = list1;
list1 = list1.next;
temp = temp.next;
} else {
temp.next = list2;
list2 = list2.next;
temp = temp.next;
}
}
temp.next = list1 == null ? list2 : list1;
return ans.next;
}
}
- 总结:这是链表型题目的基础题目。



