链表——(循环和递归)合并两个排序链表

题目:合并两个递增排序链表,使新链表仍然按照递增排序。


方法一:

基于递归的方法,链表first和链表second各有m和n个结点,新链表的头结点为两个链表中头结点较小

的一个,当找到该头结点时(假设为first的头结点),仍需对first的m-1个结点和second的n个结点合并。

可以看出,子问题和原问题相同,因此可以利用递归解决。

代码如下:

/**
 * 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 first, ListNode second) {
        
        if(first==null)
            return second;
        if(second==null)
            return first;
        
        ListNode head=null;
        
        if(first.val<second.val)
            {
            head=first; 
            head.next=mergeTwoLists(first.next,second);
        }else
            {
            head=second;
             head.next=mergeTwoLists(first,second.next);
        }
        return head;
    }
}


方法二:

基于循环,对两个链表的结点逐个进行比较。

代码如下:

public class Solution {
    public ListNode mergeTwoLists(ListNode first, ListNode second) {
        if(first==null)
            return second;
        if(second==null)
            return first;
        
        ListNode head=null;
        ListNode temp=null;
        ListNode cur =null;
        
        //当first和second都没有到各自链表的结尾;
        while(first!=null&&second!=null)
            {
            if(first.val<second.val)
                {
                temp=first;
                first=first.next;
            }else
                {
                temp=second;
                second=second.next;
            }
            
            if(head==null)
                {
                head=temp;
                cur=temp;
            }else
                {
                cur.next=temp;
                cur=temp;
            } 
        }
        //first和second中的一个到链表的结尾;
        if(first!=null)
            {
            cur.next=first;
        }else
            {
            cur.next=second;
        }
        
        return head;     
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值