leetcode -- 445. Add Two Numbers II 【栈 + 正整数相加】

来源:互联网 发布:淘宝自己退货率怎么看 编辑:程序博客网 时间:2024/05/27 14:13

题目

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 8 -> 0 -> 7

题意

给定两个非空列表,表示两个非负整数。最高位在第一个,每一个结点包含着一个数字。将这两个数字相加,并且以链表的形式返回。

分析及解答


/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        Stack<Integer> s1 = new Stack<>();Stack<Integer> s2 = new Stack<>();Stack<Integer> result = new Stack<>();while(l1 != null){s1.push(l1.val);l1 = l1.next;}while(l2 != null){s2.push(l2.val);l2 = l2.next;}int pre = 0;int num1 = 0;int num2 = 0;while(!s1.isEmpty() || !s2.isEmpty() || pre > 0){num1 = (s1.isEmpty() ? 0:s1.pop());num2 = (s2.isEmpty() ? 0:s2.pop());result.push((num1 + num2 +pre)%10);pre = (num1 + num2 +pre)/10;}ListNode p = new ListNode(result.pop());ListNode head =p;while(!result.isEmpty()){p.next = new ListNode(result.pop());p = p.next;}return head;    }}


原创粉丝点击