保存链表:在Java中保存链表,在LeetCode中添加两个数字。

huangapple go评论72阅读模式
英文:

Saving the linked list in java in leetcode add two numbers

问题

我正在LeetCode上解决这个问题。然而,我在返回链表时遇到了问题。

给你两个表示两个非负整数的非空链表,数字以逆序存储,每个节点包含一个数字。将这两个数字相加并以链表形式返回结果。

你可以假设这两个数都不会以零开头,除了数字0本身。

示例:

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

# 单链表  #


/**
 * 链表节点的定义。
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

问题

在代码的最后部分,我意识到无法保存插入的数字在 head 中。我注意到 head.next = new ListNode(sum %10); 正在覆盖我的节点。我该如何保存链表状态?

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        StringBuilder a = new StringBuilder();
        StringBuilder b = new StringBuilder();
        
        ListNode temp = l1;
        ListNode temp2 = l2;
        while(temp != null || temp2 != null) {
            a.append(temp.val);
            b.append(temp2.val);
            temp = temp.next;
            temp2 = temp2.next;
        }
       int sum =  Integer.parseInt(a.reverse().toString()) + Integer.parseInt(b.reverse().toString());
   
       ListNode head = new ListNode(0); 
       
        while(sum != 0) {
           head.next = new ListNode(sum % 10);
           head = head.next;
           sum /= 10;
        }
         
        return head;
    }
英文:

I am solving this question on Leetcode. However, I have an issue with returning inked list.

> You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order 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.

> Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

# Singly Linked List  #


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

The issue

At the last part of my code, I realize I am not able to save the inserted numbers in head. I notice that the head.next = new ListNode(sum %10);` is overwriting my node. How do I go about saving the state of my list?

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        StringBuilder a = new StringBuilder();
        StringBuilder b = new StringBuilder();
        
        ListNode temp = l1;
        ListNode temp2 = l2;
        while(temp != null || temp2 != null) {
            a.append(temp.val);
            b.append(temp2.val);
            temp = temp.next;
            temp2 = temp2.next;
        }
       int sum =  Integer.parseInt(a.reverse().toString()) +                                                     Integer.parseInt(b.reverse().toString());
   
       ListNode head = new ListNode(0); 
       
        while(sum != 0) {
           head.next = new ListNode(sum % 10);
           head = head.next;
           sum /= 10;
        }
         
        return head;
    }

答案1

得分: 1

We'd use a sentinel node (right before head or start node) for solving this problem. Then, we'd just return sentinel.next; instead of return head;.

This'll pass through:

public final class Solution {
    public static final ListNode addTwoNumbers(
        ListNode l1, 
        ListNode l2
    ) {
        int left = 0;
        ListNode sentinel = new ListNode(0);
        ListNode tail = sentinel;

        while (!(l1 == null && l2 == null && left == 0)) {
            final int add1 = l1 != null ? l1.val : 0;
            final int add2 = l2 != null ? l2.val : 0;
            final int sum = add1 + add2 + left;
            left = sum / 10;
            final ListNode tempNode = new ListNode(sum % 10);
            tail.next = tempNode;
            tail = tempNode;

            if (l1 != null) {
                l1 = l1.next;
            }

            if (l2 != null) {
                l2 = l2.next;
            }

        }

        return sentinel.next;
    }
}

References

  • For additional details, please see the Discussion Board which you can find plenty of well-explained accepted solutions in there, with a variety of languages including efficient algorithms and asymptotic time/space complexity analysis1, 2.
英文:

We'd use a sentinel node (right before head or start node) for solving this problem. Then, we'd just return sentinel.next; instead of return head;.

This'll pass through:

public final class Solution {
    public static final ListNode addTwoNumbers(
        ListNode l1, 
        ListNode l2
    ) {
        int left = 0;
        ListNode sentinel = new ListNode(0);
        ListNode tail = sentinel;

        while (!(l1 == null && l2 == null && left == 0)) {
            final int add1 = l1 != null ? l1.val : 0;
            final int add2 = l2 != null ? l2.val : 0;
            final int sum = add1 + add2 + left;
            left = sum / 10;
            final ListNode tempNode = new ListNode(sum % 10);
            tail.next = tempNode;
            tail = tempNode;

            if (l1 != null) {
                l1 = l1.next;
            }

            if (l2 != null) {
                l2 = l2.next;
            }

        }

        return sentinel.next;
    }
}

References

  • For additional details, please see the Discussion Board which you can find plenty of well-explained accepted solutions in there, with a variety of languages including efficient algorithms and asymptotic time/space complexity analysis<sup>1, 2</sup>.

答案2

得分: 1

问题出在head = head.next;这一行。这会覆盖变量head,这就是为什么程序总是返回“最后一个”节点。解决方案是返回一个不同的变量。
然而,还有另一个问题。即你返回的链表总是以0结尾。例如,对于你给出的示例输入,它返回0->7->0->8。这是因为你总是将链表初始化为0。
这里是一个可能的(不太优雅,但快速)解决方案。

编辑

为了防止在长度不同的链表上出现空指针异常,字符串的生成被放入一个方法中,每个链表调用一次。
添加了对空节点情况的处理。

编辑2
对函数进行了重新设计,并处理了空节点的情况。

public String nodeToString(ListNode l){
    StringBuilder a = new StringBuilder();
    ListNode temp = l;
    while(temp != null ) {
        a.append(temp.val);
        temp = temp.next;
    }
    return a.reverse().toString();
}

public Integer nodeToInt(ListNode l){
    String a = nodeToString(l);
    Integer ret = 0;
    if(a.length() > 0)
        ret = Integer.parseInt(a);
    return ret;
}

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    Integer a = nodeToInt(l1);
    Integer b = nodeToInt(l2);
    int sum = a + b;   
    ListNode head = new ListNode(sum % 10); 
    sum /= 10;
       
    ListNode retVal = head;
       
    while(sum != 0) {
        head.next = new ListNode(sum % 10);
        head = head.next;
        sum /= 10;
    }
         
    return retVal;
}
英文:

The problem is due to the head = head.next; line. This is overwriting the variable head, that's why the program returns always the 'last' node. The solution is to return a different variable.
However, there's another problem. I.E. your returned list has always a tailing 0. I.E. for the example imput you give, it returns 0->7->0->8 . This because you always initialize your list to 0.
Here a possible (not so elegant, but quick), solution.

EDIT

In order to prevent NullPointerException on lists of different sizes, the generation of the strings is put in a method, called once per list.
Added management of case of null node

EDIT 2
Added a reingeneering of functions and the management of cases of null nodes

public String nodeToString(ListNode l){
	StringBuilder a = new StringBuilder();
	ListNode temp = l;
    while(temp != null ) {
        a.append(temp.val);
        temp = temp.next;
        
    }
    return a.reverse().toString();
}

public Integer nodeToInt(ListNode l){
	String a=nodeToString(l);
	Integer ret=0;
	if(a.length()&gt;0)
		ret=Integer.parseInt(a);
	return ret;
}


public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
    
   Integer a=nodeToInt(l1);
   Integer b=nodeToInt(l2);
   int sum =  a+b;   
   ListNode head = new ListNode(sum % 10); 
   sum /= 10;
   
   ListNode retVal=head;
   
    while(sum != 0) {
       head.next = new ListNode(sum % 10);
       head = head.next;
       sum /= 10;
    }
     
    return retVal;
}

答案3

得分: 1

为什么不在迭代 l1 和 l2 时构建结果列表呢?我们不需要 StringBuilder,parseInt 或者 reverse()

运行时间:1 毫秒,超过了 100.00% 的 Java 提交记录,用于两数相加。
内存使用:39.6 MB,少于 75.33% 的 Java 提交记录,用于两数相加。

以下是我的解决方案:

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(0);
        ListNode ret = res;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int a = l1 == null ? 0 : l1.val;
            int b = l2 == null ? 0 : l2.val;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
            res.next = new ListNode((a + b + carry) % 10);
            res = res.next;
            carry = ((a + b + carry) / 10);
        }
        if (carry != 0) res.next = new ListNode(carry);
        return ret.next;
    }
}
英文:

Why not build the result list while iterating the l1 and l2? We don't need StringBuilder, parseInt or reverse().

Runtime: 1 ms, faster than 100.00% of Java online submissions for Add Two Numbers.
Memory Usage: 39.6 MB, less than 75.33% of Java online submissions for Add Two Numbers.

Here is my solution <br>

class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode res = new ListNode(0);
    ListNode ret = res;
    int carry = 0;
    while (l1 != null || l2 != null) {
        int a = l1 == null ? 0 : l1.val;
        int b = l2 == null ? 0 : l2.val;
        l1 = l1 == null ? null : l1.next;
        l2 = l2 == null ? null : l2.next;
        res.next = new ListNode((a + b + carry) % 10);
        res = res.next;
        carry = ((a + b + carry) / 10);
    }
    if (carry != 0) res.next = new ListNode(carry);
    return ret.next;
}

}

huangapple
  • 本文由 发表于 2020年8月8日 10:04:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63311139.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定