https://oj.leetcode.com/problems/merge-two-sorted-lists/
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
public ListNode mergeTwoLists(ListNode l1, ListNode l2)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
这一题其实很简单的,用一个tmp指针进行串联,每一步都走向较小的那一方,然后让较小的那一方往前走就可以了。当走完一边之后,就把另一边剩下的串上即可。直接给代码吧,关于链表的题目都不会很难,就是需要处理的边界条件需要小心:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null || l2 == null)
return l1 == null ? l2 : l1;
ListNode head = null, tmp = null;
ListNode tmp1 = l1, tmp2 = l2;
while(tmp1 != null || tmp2 != null){
if((tmp2 == null && tmp1 != null) || (tmp1 != null && tmp1.val < tmp2.val)){
if(head == null){
head = tmp1;
tmp = head;
tmp1 = tmp1.next;
}else{
tmp.next = tmp1;
tmp = tmp.next;
tmp1 = tmp1.next;
}
}else{
if(head == null){
head = tmp2;
tmp = head;
tmp2 = tmp2.next;
}else{
tmp.next = tmp2;
tmp = tmp.next;
tmp2 = tmp2.next;
}
}
}
return head;
}