leetcode地址: leetcode.cn/problems/me…
原题描述:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
解题思路:
非常简单的一道题,双指针判断相加即可。。leetcode的官方题解的思路一不太推荐。。
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head = null;
ListNode index = head;
while (list1 != null || list2 != null) {
ListNode add = null;
if (list1 == null) {
add = list2;
list2 = list2.next;
} else if (list2 == null) {
add = list1;
list1 = list1.next;
} else {
if(list1.val <= list2.val){
add = list1;
list1 = list1.next;
}else{
add = list2;
list2 = list2.next;
}
}
if(head==null){
head = add;
index = head;
}else{
index.next = add;
index = index.next;
}
}
return head;
}
}