#21 Merge Two Sorted Lists

Description

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.

Examples

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

解题思路

我用的是傻办法hhhhhh
新建一个list,然后对两边进行判断,选取较小的那个放到新list里面,最后返回新list

/**
 * 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) {
        ListNode s1, s2, t;
        s1 = l1;
        s2 = l2;
        t = new ListNode(0);
        t.next = l1;
        ListNode h = t;
        while(s1 != null && s2 != null){
            t = t.next;
            if(s1.val >= s2.val){
                ListNode temp = s1.next;
                s1.next = new ListNode(s2.val);
                s1.next.next = temp;
                s2 = s2.next;
            }
            s1 = s1.next;
        }
        if(s2 != null)
            t.next = s2;
        if(s1 != null)
            t.next = s1;
        return h.next;
    }
}

其他方法

去discussion摸了一圈,有一个java跑了1ms的递归方法,哇下次要把递归也考虑进去!

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;
		}
}

其他

  • 做题的时候犯了傻,每次都返回 t -> next,导致只有只能返回一个值hhhhhh,看了半天才反应过来开始的时候应该有一个指向 t 的 head 用于最后的返回
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值