[算法学习]合并两个排序的链表

32 篇文章 0 订阅
29 篇文章 10 订阅

问题描述: 合并两个排序的链表。

解法一:用递归

解法: 递归比较结点大小:每次递归,取出两个链表的头结点来比较,比较小的结点加入新链表中。


参考代码如下

/**
 * 用递归
 * @param head1
 * @param head2
 * @return
 */
public static ListNode merge(ListNode head1, ListNode head2)
{
    if(head1==null)
    {
        return head2;
    }
    if(head2==null)
    {
        return head1;
    }
    ListNode head;
    if(head1.value<head2.value)
    {
        head=head1;
        head.next=merge(head1.next, head2);
    }
    else
    {
        head=head2;
        head.next=merge(head1, head2.next);
    }
    return head;
}

解法二:用循环

解法: 使用指针移动的方式来遍历两个链表。每次两个指针停止,进行结点比较,较小的结点加到新链表中。


参考代码如下

/**
 * 用循环
 * @param head1
 * @param head2
 * @return
 */
public static ListNode merge1(ListNode head1, ListNode head2)
{
    if (head1 == null)
    {
        return head2;
    }
    if (head2 == null)
    {
        return head1;
    }
    ListNode head;
    if (head1.value < head2.value)
    {
        head = head1;
        head1 = head1.next;
    }
    else
    {
        head = head2;
        head2 = head2.next;
    }
    ListNode move = head;
    while (head1 != null || head2 != null)
    {
        if (head1 == null)
        {
            move.next = head2;
            head2 = head2.next;
        }
        else if (head2 == null)
        {
            move.next = head1;
            head1 = head1.next;
        }
        else if (head1.value < head2.value)
        {
            move.next = head1;
            head1 = head1.next;
        }
        else
        {
            move.next = head2;
            head2 = head2.next;
        }
        if(move.value>move.next.value)
        {
            System.err.println("输入的链表不是有序的");
            return null;
        }
        move = move.next;
    }
    return head;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值