leetcode 445. Add Two Numbers I

本文详细解析了一种解决链表加法问题的算法,通过使用栈存储链表元素,实现链表数值相加并处理进位。算法采用头插法构建结果链表,确保时间复杂度为O(n),空间复杂度亦为O(n)。

算法分析:
分别将两个链表存入栈中,然后将两个栈中的元素依次同时弹出,设置一个进位标记carry,两个元素和进位carry相加得到结果value,更新carry值,更新value值保证其小于10,采用头插法插入链表中。当2个栈中的一个为空时,则退出循环。然后继续插入栈不为空的元素节点,直到该栈为空。最后检查进位carry值,若carry不为零,则将carry插入链表中。时间复杂度O(n),空间复杂度O(n)。

参考代码

//leetcode   445. Add Two Numbers II
	public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> input1 = new Stack<Integer>();
        Stack<Integer> input2 = new Stack<Integer>();
        while(l1!=null){
        	input1.push(l1.val);
        	l1 = l1.next;
        }
        while(l2!=null){
        	input2.push(l2.val);
        	l2 = l2.next;
        }
        int carry = 0;
        ListNode head = null;
        while(!input1.empty()&&!input2.empty()){
        	int value = input1.pop()+input2.pop()+carry;
        	carry = value/10;
        	value = value%10;
        	ListNode node = new ListNode(value);
        	if(head==null){
        		head = node;
        	}else{
        		node.next = head;
        		head = node;
        	}
        }
        while(!input1.empty()){
        	int value = input1.pop()+carry;
        	carry = value/10;
        	value = value%10;
        	ListNode node = new ListNode(value);
        	node.next = head;
    		head = node;
        }
        while(!input2.empty()){
        	int value = input2.pop()+carry;
        	carry = value/10;
        	value = value%10;
        	ListNode node = new ListNode(value);
        	node.next = head;
    		head = node;
        }
        if(carry!=0){
        	ListNode node = new ListNode(carry);
        	node.next = head;
    		head = node;
        }
        return head;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值