合并两个有序链表
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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
迭代法:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// 两条链表都为null 直接返回null
if(l1==null&&l2==null)
return null;
if(l1==null) // l1为null 直接返回l2
return l2;
if(l2==null) // l2 为null, 直接返回l1
return l1;
// cur 保存当前尾节点 temp 保存即将接上的节点 head 为头结点
ListNode cur=null,temp=null,head=null;
while(l1!=null&&l2!=null)
{
if(l1.val>=l2.val)
{
temp = l2;
l2 = l2.next;
}
else
{
temp = l1;
l1 = l1.next;
}
if(head==null)
cur = head = temp;
else
{
cur.next = temp;
cur = temp;
}
}
if(l1==null)
cur.next = l2;
else
cur.next = l1;
return head;
}
}
递归法:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;
if(l1.val>=l2.val)
{
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}else
{
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}
}
}
本文介绍了一种算法,用于合并两个已排序的链表并生成一个新的排序链表。提供了两种实现方式,分别是迭代法和递归法。迭代法通过比较两个链表的节点值,将较小的节点插入到新的链表中;递归法则通过比较当前节点的值,将较小的节点作为新链表的头节点,然后递归地处理剩余部分。
1029

被折叠的 条评论
为什么被折叠?



