Java日记2018-07-20

2018-07-20  本文已影响0人  hayes0420

一 Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse
order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8

package com.lyc.letcode;



public class Solution0720 {
    public static ListNode add2number(ListNode n1,ListNode n2){
        if (n1==null){
            return n2;
        } 
        if(n2==null) return n1;
        return add2numCore(n1,n2,0);
    }
    public static ListNode add2numCore(ListNode l1,ListNode l2,int carry){
        if(l1==null && l2==null && carry==0) return null;
        ListNode res = new ListNode(carry);
        if(l1!=null) res.val+=l1.val;
        if(l2!=null) res.val+= l2.val;
        res.next = add2numCore(l1.next,l2.next,res.val/10);
        res.val = res.val%10;
        return res;
        
    }
    
    public static void  main(String[] args){
        ListNode l1 = new ListNode(2);
        ListNode l2 = new ListNode(4);
        ListNode l3 = new ListNode(3);
        ListNode l5 = new ListNode(5);
        ListNode l6 = new ListNode(6);
        ListNode l7 = new ListNode(4);
        l1.next = l2;
        l2.next = l3;
        l5.next = l6;
        l6.next = l7;
        
        ListNode rt = add2number(l1,l5);
        System.out.println(rt.next.next.val);
    }

}

二 Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced
BST.

上一篇下一篇

猜你喜欢

热点阅读