• Two Lists Sum Advanced


    Source

    Given two numbers represented by two linked lists, write a function that returns sum list.
    The sum list is linked list representation of addition of two input numbers.
    
    Example
    
    Input:
      First  List: 5->6->3  // represents number 563
      Second List: 8->4->2  // represents number 842
    Output
      Resultant list: 1->4->0->5  // represents number 1405
    
    Challenge
    
    Not allowed to modify the lists.
    Not allowed to use explicit extra space.

    题解1 - 反转链表

    在题 Two Lists Sum 的基础上改了下数位的表示方式,前者低位在前,高位在后,这个题的高位在前,低位在后。很自然地可以联想到先将链表反转,而后再使用 Two Lists Sum 的解法。

    Java

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode reverse(ListNode head) {
            ListNode prev = null;
            while (head != null) {
                ListNode next = head.next;
                head.next = prev;
                prev = head;
                head = next;
            }
            return prev;
        }
    
        public ListNode addLists(ListNode l1, ListNode l2) {
            l1 = reverse(l1);
            l2 = reverse(l2);
            ListNode dummy = new ListNode(0);
            ListNode curr = dummy;
            int carry = 0;
    
            while ((l1 != null) || (l2 != null) || (carry != 0)) {
                int l1_val = (l1 != null) ? l1.val : 0;
                int l2_val = (l2 != null) ? l2.val : 0;
                int sum = carry + l1_val + l2_val;
            // update carry
                carry = sum / 10;
                curr.next = new ListNode(sum % 10);
    
                curr = curr.next;
                if (l1 != null) l1 = l1.next;
                if (l2 != null) l2 = l2.next;
            }
    
            return reverse(dummy.next);
        }
    }

    源码分析

    参考 Two Lists Sum

    复杂度分析

    参考 Two Lists Sum

  • 相关阅读:
    ViewData,ViewBag,TempData
    http和https
    Array与ArrayList
    程序员与书和视频
    技术学习的方法研究
    文章发布声明
    面向对象JAVA多态性
    嵌入式开发总结
    CSDN博客代码显示乱码的原因
    将Windows的桌面目录设置到D盘
  • 原文地址:https://www.cnblogs.com/lyc94620/p/16062712.html
Copyright © 2020-2023  润新知