java - leetcode中java保存链表加两个数
问题描述
我正在 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;
}
解决方案
问题是由于head = head.next;
线路。这是覆盖变量 head,这就是程序总是返回“最后一个”节点的原因。解决方案是返回一个不同的变量。但是,还有另一个问题。IE 你返回的列表总是有一个拖尾 0。IE 对于你给出的示例输入,它返回 0->7->0->8 。这是因为您总是将列表初始化为 0。这是一个可能的(不是那么优雅,但很快)的解决方案。
编辑
为了防止不同大小的列表出现 NullPointerException,字符串的生成放在一个方法中,每个列表调用一次。增加对空节点大小写的管理
编辑 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;
}
推荐阅读
- reactjs - mui-datatables 搜索不适用于 customBodyRender 列
- javascript - Quasar Vue 存储忽略状态属性
- python - 如何更有效地打印数独网格
- python - 如何解决 Spacy POS 属性 E1005 错误
- mysql - 当sql中的某些字符不同时如何放入同一组
- matlab - writetable() 替代更易读的表格摘要?
- python - 异步使用authlib的httpx客户端的例子
- c# - c# 数组元素为空,但 if(array[nr] != null) 为真!为什么?
- reactjs - redux - React 应用程序中的全局数据层 - 如何成为一个好的实践?
- docker-compose - 如何强制容器无限期地等待它依赖的服务?