一、问题描述
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; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;
ListNode result=new ListNode(0);
ListNode tem=result;
while(l1!=null && l2!=null){
if(l1.val<l2.val)
{
tem.next=l1;//tem的next指向l1
l1=l1.next;//l1指向自己的下一个元素
}
else{
tem.next=l2;
l2=l2.next;
}
tem=tem.next; //tem指向下刚才添加的元素,以便一下次添加
}
if(l1==null && l2!=null){
tem.next=l2;
}
if(l1!=null && l2==null){
tem.next=l1;
}
return result.next;
}
}
论坛里面提供了一种递归解法,因为本人对递归不是很明白,粘过来膜拜一下
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else{
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}