【发布时间】:2020-08-08 02:04:30
【问题描述】:
我正在 Leetcode 上解决这个问题。但是,我在返回着墨列表时遇到了问题。
给定两个代表两个非负整数的非空链表。这些数字以相反的顺序存储,它们的每个节点都包含一个数字。将两个数字相加并作为链表返回。
您可以假设这两个数字不包含任何前导零,除了数字 0 本身。
例子:
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; }
* }
*/
问题
在我的代码的最后一部分,我意识到我无法将插入的数字保存在 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;
}
【问题讨论】:
标签: java linked-list singly-linked-list