zoukankan      html  css  js  c++  java
  • 445. 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

    /**
     * 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) {
            ListNode reverseL1 = reverseList(l1);
            ListNode reverseL2 = reverseList(l2);
            int digit = 0;
            int curry = 0;
            ListNode dummy = new ListNode(0);
            ListNode pre = dummy;
            while(reverseL2 != null || reverseL1 != null || curry != 0){
                int index1 = (reverseL1 == null? 0 : reverseL1.val);
                int index2 = (reverseL2 == null? 0 : reverseL2.val);
                digit = (index1 + index2 + curry) % 10;
                curry = (index1 + index2 + curry) / 10;
                dummy.next = new ListNode(digit);
                dummy = dummy.next;
                if(reverseL1 != null) reverseL1 = reverseL1.next;
                if(reverseL2 != null) reverseL2 = reverseL2.next;
            }
            return reverseList(pre.next);
        }
        public ListNode reverseList(ListNode head){
            if(head== null || head.next == null) return head;
            ListNode dummy = new ListNode(0);
            dummy.next =  head;
            ListNode cur = head.next;
            while(cur != null){
                head.next = cur.next;
                cur.next = dummy.next;
                dummy.next = cur;
                cur = head.next;
            }
            return dummy.next;
            
        }
    }
  • 相关阅读:
    使用StreamHttpResponse和FileResponse下载文件的注意事项及文件私有化
    Django中@login_required用法简介
    Django之template
    单链表反转的原理和python代码实现
    两个队列实现栈,两个栈实现队列
    Linux--5 mariadb和redis的安装
    Linux--4
    Linux--3
    Linux--2 Linux之文档与目录结构、shell基本命令
    Linux--1 初识
  • 原文地址:https://www.cnblogs.com/joannacode/p/6108133.html
Copyright © 2011-2022 走看看