zoukankan      html  css  js  c++  java
  • Leetcode: Add Two Numbers II

    You are given two linked lists representing two non-negative numbers. 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

    The key of this problem is to think of using Stack

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    11         Stack<ListNode> st1 = new Stack<ListNode>();
    12         Stack<ListNode> st2 = new Stack<ListNode>();
    13         while (l1 != null) {
    14             st1.push(l1);
    15             l1 = l1.next;
    16         }
    17         while (l2 != null) {
    18             st2.push(l2);
    19             l2 = l2.next;
    20         }
    21         ListNode dummy = new ListNode(-1);
    22         int carry = 0;
    23         while (st1.size()!=0 || st2.size()!=0 || carry!=0) {
    24             int sum = 0;
    25             if (st1.size() != 0) sum += st1.pop().val;
    26             if (st2.size() != 0) sum += st2.pop().val;
    27             if (carry != 0) sum += carry;
    28             ListNode newNode = new ListNode(sum%10);
    29             newNode.next = dummy.next;
    30             dummy.next = newNode;
    31             carry = sum / 10;
    32         }
    33         return dummy.next;
    34     }
    35 }
  • 相关阅读:
    在Ubuntu中通过update-alternatives切换软件版本
    SCons: 替代 make 和 makefile 及 javac 的极好用的c、c++、java 构建工具
    mongodb 的使用
    利用grub从ubuntu找回windows启动项
    How to Repair GRUB2 When Ubuntu Won’t Boot
    Redis vs Mongo vs mysql
    java script 的工具
    python 的弹框
    how to use greendao in android studio
    python yield的终极解释
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6178390.html
Copyright © 2011-2022 走看看