/**
* 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.
*
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*
* 题目大意:合并有序链表,注意,链表有可能是空的
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
return solve1(l1, l2);
}
//=========================== solve1 ===============================
//合并链表,只要注意空链的处理就可以了
private ListNode solve1(ListNode l1, ListNode l2) {
//处理空链表
if(l1 == null)
return l2;
if(l2 == null)
return l1;
ListNode result = null;
ListNode head = null;
//先连上头结点
if(l1.val < l2.val){
result = l1;
l1 = l1.next;
}else{
result = l2;
l2 = l2.next;
}
head = result;
//对两条链每一个元素进行判断、合并,直到某一条为空
while(l1!=null && l2!=null){
if(l1.val < l2.val){
result.next = l1;
l1 = l1.next;
}else{
result.next = l2;
l2 = l2.next;
}
result = result.next;
}
//若l1为空,则l2可能有剩余
if(l1 == null)
result.next = l2;
//若l2为空,则l1可能有剩余
if(l2 == null)
result.next = l1;
return head;
}
}
LeetCode:Merge Two Sorted Lists
最新推荐文章于 2021-12-30 01:40:48 发布