0
点赞
收藏
分享

微信扫一扫

链表相加(二)

半夜放水 2022-03-12 阅读 75

描述

假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。

给定两个这种链表,请生成代表两个整数相加值的结果链表。

数据范围:0 \le n,m \le 10000000≤n,m≤1000000,链表任意值 0 \le val \le 90≤val≤9
要求:空间复杂度 O(n)O(n),时间复杂度 O(n)O(n)

例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。

 

public class Solution {
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        LinkedList<Integer> list1 = new LinkedList<>();
        LinkedList<Integer> list2 = new LinkedList<>();
        putData(list1 ,head1);
        putData(list2 ,head2);
        ListNode newNode=null;
        ListNode head =null;
        int carry =0;
        while(!list1.isEmpty()|| !list2.isEmpty()|| carry!=0){
            int x =(list1.isEmpty())?0:list1.pop();
            int y =(list2.isEmpty()?0:list2.pop());
            int sum =x+y+carry;
            carry = sum/10;
            newNode =new ListNode(sum%10);
            newNode.next=head;
            head =newNode;
        }
        return head;
    }
    private static void putData(LinkedList<Integer> s1 ,ListNode head1){
        if (s1 == null )s1 =new LinkedList<>();
        while( head1!=null ){
s1.push(head1.val);
        head1 =head1.next;}
    }
}

点击查看出处

举报

相关推荐

0 条评论