【问题标题】:Adding Values to a LinkedList Not Working向 LinkedList 添加值不起作用
【发布时间】:2018-06-24 15:36:11
【问题描述】:

我正在尝试每天在 leetcode 上做一个编程问题以改进我的编程,并且在下面的问题中添加到 LinkedList 时遇到问题。我想知道是否有人可以给我一些指示。我知道我的答案不是最有效的,我只是想从某个地方开始并努力工作。该方法中的所有内容都是我迄今为止所做的。非常感谢任何帮助。

///

给定两个代表两个非负整数的非空链表。这些数字以相反的顺序存储,它们的每个节点都包含一个数字。将两个数字相加并作为链表返回。

这是一张带有可能输出示例的图片: https://imgur.com/a/g9rlb

您可以假设这两个数字不包含任何前导零,除了数字 0 本身。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

    ListNode l3 = new ListNode(-1);
    ListNode curr = new ListNode(-1);
    ListNode newNode = new ListNode(-1);

 // Take numbers from linkedList and store in strings
    String s1 = "";
    String s2 = "";
// String values after being reveresed in the right direction.
    String sR1 = "";
    String sR2 = "";

    while(l1 != null) {

        s1 += l1.val;
        l1 = l1.next;
    }
    while(l2 != null) {

        s2 += l2.val;
        l2 = l2.next;
    }

    //check
    System.out.println(s1);
    System.out.println(s2);

    //reverse the string;

    for(int i = s1.length()-1; i >= 0; i--) {

        sR1 += s1.charAt(i);
    }
      for(int j = s2.length()-1; j >= 0; j--) {

        sR2 += s2.charAt(j);
    }

//Adding the numbers together to get the final value.
    int n3 = Integer.parseInt(sR1) + Integer.parseInt(sR2);
//Converting ints to string so i can parse them into characters that will eventually be parsed into an int to return back to the LinkedList
    String fin = Integer.toString(n3);
    System.out.println(fin);


//adding the values to my final linked list that i'd be returning here.       This is the part that isn't working.
    for(int i = 0; i < fin.length()-1; i++){

    String s = String.valueOf(fin.charAt(i)); 

       int num = Integer.parseInt(s);

        newNode = new ListNode(num);

        if(l3.val == -1) {

            l3 = newNode;
        }
        else {
            curr = l3;

            while(curr.next != null){
                curr = curr.next;
            }
            curr.val = num;
        }

    }
    return l3;
}

【问题讨论】:

  • “我知道我的答案不是最有效的,我只是想从某个地方开始并努力工作。该方法中的所有内容都是我迄今为止所做的。我非常感谢任何帮助." -- 抱歉,这不是 StackOverflow 的工作方式。请访问help center 并阅读How to Ask。您应该解释什么是无效的,并提出一个具体的问题。
  • 嗨 Jim,如上所述,我在向 LinkedList 对象添加新值时遇到了问题。我说它效率不高,因为我创建了很多临时字符串并且不希望它成为对话的中心。我什至评论了我出错的部分。代码应该一直工作到那里,我已经用打印语句对其进行了调试。一旦我添加到 LinkedList 工作,程序应该按预期执行。
  • 然后尝试使用 StringBuilder 对象
  • “在下面的问题中添加到 LinkedList 时遇到问题” -- 这还不够。请准确说明您预计会发生什么以及实际会发生什么,并描述您已完成哪些故障排除以及您发现了什么。您是否在 IDE 调试器中单步执行了代码?你能指出行为偏离你预期的地方吗?如果您需要帮助,您需要让其他人轻松帮助您。只是将您的代码转储到一个问题中并本质上说“我不知道出了什么问题,请调试这个”是题外话。

标签: java linked-list singly-linked-list


【解决方案1】:

也许是这样的?这里的概念是直截了当的。 要求是反转节点并添加它们。这意味着您只需要选择正确的数据结构来满足此要求,从而为您提供后进先出?堆。现在您已经将数据放入堆栈中,只需从堆栈中弹出项目并将其相加即可获得预期结果。 有很多方法可以解决这个问题,使用 ArrayList、使用 LinkedList 或普通的旧数组,但尝试将问题与已知的数据结构相关联并以这种方式解决它会给你一致的有意义的输出。我本可以向您指出这个概念,但是拥有此代码将帮助您思考如何根据用户要求解决特定问题。干杯,希望对您有所帮助。

import java.util.Scanner;
import java.util.Stack;

public class AddTuple {
    public static void main(String[] args) {
        Stack<Integer> leftTuple = new Stack<Integer>();
        Stack<Integer> rightTuple = new Stack<Integer>();

        populateTuple(leftTuple, rightTuple, 3);
        Stack<Integer> result = addTuples(leftTuple, rightTuple);
        System.out.print("Output: {");
        int i = 0;
        while (!result.isEmpty()) {
            if (i != 0) {
                System.out.print(", ");
            }
            System.out.print(result.pop());
            i++;
        }
        System.out.println("}");
    }

    private static void populateTuple(Stack<Integer> leftTuple, Stack<Integer> rightTuple, int count) {
        Scanner scanner = new Scanner(System.in);
        try {
            System.out.print("Input: ");
            String input = scanner.nextLine();
            if (input == null || !input.contains("+") || !input.contains("{")) {
                throw new RuntimeException("Usage: {x,y,z} + {a,b,c}");
            }
            String[] operandSplit = input.split("\\+");
            String left = operandSplit[0].trim();
            String right = operandSplit[1].trim();
            left = left.replaceAll("\\{", "");
            left = left.replaceAll("\\}", "");
            right = right.replaceAll("\\{", "");
            right = right.replaceAll("\\}", "");

            String[] leftSplit = left.split(",");
            String[] rightSplit = right.split(",");

            for (int i = 0; i < leftSplit.length; i++) {
                leftTuple.push(Integer.parseInt(leftSplit[i].trim()));
            }

            for (int i = 0; i < rightSplit.length; i++) {
                rightTuple.push(Integer.parseInt(rightSplit[i].trim()));
            }
        } finally {
            scanner.close();
        }
    }

    private static Stack<Integer> addTuples(Stack<Integer> leftTuple, Stack<Integer> rightTuple) {
        Stack<Integer> result = new Stack<Integer>();
        int carryForward = 0;
        while (!leftTuple.isEmpty()) {
            int addition = leftTuple.pop() + rightTuple.pop() + carryForward;
            if (addition > 9) {
                carryForward = 1;
                addition = 10 - addition;
            }
            result.push(addition);
        }
        return result;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多