add two linked list as integer

本文介绍了一种解决两个链表表示的大数相加问题的方法。通过使用两个栈来分别存储链表中的数字,实现从低位到高位逐位相加,并处理进位问题,最终将结果以链表形式返回。

Question:

You have two numbers represented by a linked list, where each node contains a single digit. Write a function that adds the two numbers and returns the sum as a linked list.

EXAMPLE:

input: (3 -> 1 -> 5), (5 -> 9 -> 2)

output: 9 -> 0 -> 7

Analyze:

use two stacks to store the numbers in the list, and then the last number of the lists will be on the top of the stacks, we pop the stack and add the numbers, and save the result into the linked list.

Code:

public static LinkedList addList(Node h1, Node h2) {
	//save the numbers in the list to stacks
	Stack<Node> s1 = new Stack<Node>();
	Stack<Node> s2 = new Stack<Node>();
	
	while(h1 != null) {
		s1.push(h1);
		h1 = h1.next;
	}
	while(h2 != null) {
		s2.push(h2);
		h2 = h2.next;
	}
	//LinkedList saves the result
	LinkedList list = new LinkedList();
	
	int sum = 0;
	int carry = 0;
	
	while(!s1.empty() && !s1.empty()) {
		sum = s1.pop().data + s2.pop().data + carry;
		carry = sum / 10;
		sum = sum % 10;
		list.addFirst(sum);
	}
	
	while(!s1.empty()) {
		sum = s1.pop().data + carry;
		carry = sum / 10;
		sum = sum % 10;
		list.addFirst(sum);
	}
	
	while(!s2.empty()) {
		sum = s1.pop().data + carry;
		carry = sum / 10;
		sum = sum % 10;
		list.addFirst(sum);
	}
	// don't forget the carry
	if (carry != 0) list.addFirst(carry);
	
	return list;
}
http://blog.youkuaiyun.com/beiyetengqing

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值