LeetCode 445. Add Two Numbers II--两个链表均按照由尾部到头部计算两个结点数值之和,保持进位

xiaoxiao2021-02-28  103

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: (6 -> 2 -> 4 -> 3) + (5 -> 9 -> 4) Output: 6 -> 8 -> 3 -> 7 import java.util.Stack; class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public class Main { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { Stack<Integer> s1 = new Stack<Integer>(); Stack<Integer> s2 = new Stack<Integer>(); while (l1 != null) { s1.push(l1.val); l1 = l1.next; } while (l2 != null) { s2.push(l2.val); l2 = l2.next; } int sum = 0; ListNode cur = new ListNode(0); while (!s1.empty() || !s2.empty()) { if (!s1.empty()) sum += s1.pop(); if (!s2.empty()) sum += s2.pop(); cur.val = sum % 10; //为啥是“sum/10”,比如输出的[5],[5],输出应该是[1,0];如果是new ListNode(0)则输出是[0],则错误 ListNode head = new ListNode(sum/10);//先赋值为sum/10,后面cur.val = sum % 10;会赋值 head.next = cur;//新的结点的next指针指向原有的链表头指针 cur = head;//当前指针指向头指针,表示cur指向链表头部 sum /= 10;//用来进位 } return cur.val == 0 ? cur.next : cur; }//addTwoNumbers public static void main(String[] args) { // Input: (6 -> 2 -> 4 -> 3) + (5 -> 9 -> 4) // Output: 6 -> 8 -> 3 -> 7 ListNode A = new ListNode(6); A.next = new ListNode(2); A.next.next = new ListNode(4); A.next.next.next = new ListNode(3); ListNode B = new ListNode(5); B.next = new ListNode(9); B.next.next = new ListNode(4); Main main = new Main(); ListNode C = main.addTwoNumbers(A, B); System.out.println(C); } } 1563 / 1563 test cases passed. Status: Accepted Runtime: 63 ms Your runtime beats 46.11 % of java submissions.

T(n) = O(n)

转载请注明原文地址: https://www.6miu.com/read-54930.html

最新回复(0)