【问题标题】:Add two numbers which are stored as in reversed linked list form添加两个以反向链表形式存储的数字
【发布时间】:2019-10-14 18:46:11
【问题描述】:

我得到了两个代表两个非负整数的非空链表。数字以相反的顺序存储,每个节点包含一个数字。任务是将两个数字相加并将其作为链表返回。

  • 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
  • 输出:7 -> 0 -> 8
  • 解释:342 + 465 = 807

这个问题有几种解决方案。我试图通过将链表形成的数字转换为数字来解决它。我已经将列表转换为数字,但我的问题从这里开始。你得到了一个链表定义,你不能破坏它。此定义中没有默认(空)构造函数。我还不能将我的整数和转换为链表形式。这是我的代码:

public class ListNode {    //given linked -list definition. Should not be manipulated.
     int val;
      ListNode next;
     ListNode(int x) { val = x; }
}

import java.util.*;
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
       int num1 = getNumber(l1);
        int num2 = getNumber(l2);
        int sum = num1 + num2;
        return ??  //some how I should return a LinkedList where my sum is converted into it
    }



//getNumber converts given linked-lists into integers 
    public int getNumber(ListNode head) {
       ListNode tmp = head;
    int number = 0;
    int pass = 0;
    while(tmp != null) {
        number += tmp.val * Math.pow(10, pass) ;
        tmp = tmp.next;
        pass++;
    }
    return number;
}

【问题讨论】:

  • 你想把 7->0->8 放到一个新的 LinkedList 中吗?你可以创建一个新的 LinkedList 吗?您正在返回一个 ListNode 变量,它只能包含一个值

标签: java linked-list


【解决方案1】:

您需要创建一个全新的列表。

首先创建一个新的头节点。它应该包含什么? sum 的最后一位数字,对吧?所以获取sum的最后一位数字:int lastDigit = sum %10并将其放入新链接:new ListNode(lastDigit)

然后为下一个数字,下一个数字,直到sum == 0。请记住在创建每个之后将ListNode 相互链接。可能类似于prevNode.next = new ListNode(lastDigit)

【讨论】:

    【解决方案2】:

    本练习的真正目的是使用给定的数据结构来执行计算。您不应该将链接列表转换为int。为什么,这些值可能不适合int 的限制。使用链表,您可以对数以千计的数字执行操作。

    这是一个不完整的草图,可以帮助你,但不会破坏练习。

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        return addTwoNumbers(l1, l2, 0);
    }
    
    private ListNode addTwoNumbers(ListNode l1, ListNode l2, int carry) {
        // TODO: know when to stop!
        // ex: if you have reached the end of l1, then apply carry to l2, if needed, and return
        // ex: if you have reached the end of l2, then apply carry to l1, if needed, and return
    
        int val = l1.val + l2.val + carry;
        ListNode node = new ListNode(val % 10);
        node.next = addTwoNumbers(l1.next, l2.next, val / 10);
        return node;
    }
    
    private ListNode addOne(ListNode l1) {
        // TODO
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      相关资源
      最近更新 更多