链表相加.

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

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

数据范围:0≤𝑛,𝑚≤1000000,链表任意值 0≤𝑣𝑎𝑙≤9
要求:空间复杂度 𝑂(𝑛),时间复杂度 𝑂(𝑛)

public class Solution {
    //反转链表
    public ListNode ReverseList(ListNode pHead) { 
        if(pHead == null)
            return null;
        ListNode cur = pHead;
        ListNode pre = null;
        while(cur != null){
            ListNode temp = cur.next;
            cur.next = pre; 
            pre = cur; 
            cur = temp; 
        }
        return pre;
    }
    
    public ListNode addInList (ListNode head1, ListNode head2) {
        if(head1 == null) 
            return head2;
        if(head2 == null)
            return head1;
        head1 = ReverseList(head1); 
        head2 = ReverseList(head2);
        ListNode res = new ListNode(-1); 
        ListNode head = res;
 
        int carry = 0; 
        while(head1 != null || head2 != null || carry != 0){ 
            int val1 = head1 == null ? 0 : head1.val; 
            int val2 = head2 == null ? 0 : head2.val;
   
            int temp = val1 + val2 + carry; 
            carry = temp / 10; 
            temp %= 10; 
            head.next = new ListNode(temp); 
            head = head.next;
          
            if(head1 != null) 
                head1 = head1.next;
            if(head2 != null)
                head2 = head2.next;
        }
        return ReverseList(res.next); 
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值