zoukankan      html  css  js  c++  java
  • [leetcode]445. Add Two Numbers II 两数相加II


    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

    题目

    俩数用链表表示,做个加法

    思路

    1. use stack to covert input list data

    2. sum up from pop item from two stacks to a desired linkedlist

    代码

     1 class Solution {
     2     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
     3         if (l1 == null && l2 == null) return null;
     4         if (l2 == null) return l1;
     5         if (l1 == null) return l2;
     6         // use stack to convert list's order
     7         Stack<Integer> s1 = new Stack<>();
     8         Stack<Integer> s2 = new Stack<>();
     9     
    10         while (l1 != null) {
    11             s1.push(l1.val);
    12             l1 = l1.next;
    13         }
    14         
    15         while (l2 != null) {
    16             s2.push(l2.val);
    17             l2 = l2.next;
    18         }
    19         
    20         int sum = 0;
    21         ListNode head = new ListNode(0);
    22         // sum up to a new linkedlist
    23         while (!s1.isEmpty() || !s2.isEmpty()) {
    24             if (!s1.isEmpty()) sum += s1.pop();
    25             if (!s2.isEmpty()) sum += s2.pop();
    26             
    27             int val = sum % 10;
    28           
    29             ListNode node = new ListNode(0);
    30             head.val = val;
    31             node.next = head;
    32             head = node;
    33             
    34             sum /= 10;
    35         }
    36         if (sum == 0){
    37             return head.next;
    38         }
    39         head.val = sum;
    40         return head;
    41     }
    42 }
  • 相关阅读:
    MXNet.gluon——图像I/O
    ECCV2018 论文简析 Oral_1 持续更新
    hdu 3123 GCC
    hdu 2481 Toy
    hdu 3441 Rotation
    hdu 1812 Count the Tetris
    hdu 3923 Invoker
    hdu 1352 I Conduit!
    2013 ACM-ICPC长沙赛区全国邀请赛——Bottles Arrangement
    2013 ACM-ICPC长沙赛区全国邀请赛—Special equations
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9828175.html
Copyright © 2011-2022 走看看