[LeetCode 中等 链表]面试题 02.05. 链表求和

题目描述

给定两个用链表表示的整数,每个节点包含一个数位。

这些数位是反向存放的,也就是个位排在链表首部。

编写函数对这两个整数求和,并用链表形式返回结果。

示例:

输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295
输出:2 -> 1 -> 9,即912

进阶:思考一下,假设这些数位是正向存放的,又该如何解决呢?

示例:
输入:(6 -> 1 -> 7) + (2 -> 9 -> 5),即617 + 295
输出:9 -> 1 -> 2,即912

正向存放 两个栈存储链表值

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		Stack<Integer> stack1 = new Stack<>();
		Stack<Integer> stack2 = new Stack<>();
		
		putData(stack1, l1);
		putData(stack2, l2);
		ListNode newNode = null;
		ListNode head = null;
		int carry = 0;
		while(!stack1.isEmpty() || ! stack2.isEmpty() || carry != 0) {
			int x = (stack1.isEmpty()) ? 0 : stack1.pop(); 
			int y = (stack2.isEmpty()) ? 0 : stack2.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(Stack<Integer> s1, ListNode l1) {
		if (s1 == null) s1 = new Stack<>();
		while(l1 != null) {
			s1.push(l1.val);
			l1 = l1.next;
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值