【发布时间】:2020-04-25 22:50:23
【问题描述】:
我需要创建一个程序,该程序将添加 2 个单独的链表中的 2 个数字。我使程序正常工作,但最后我得到了一个额外的 -1 值,这是我不需要的。我该如何摆脱它?这里有一些上下文:
/*
Definition for singly-linked list.
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
*/
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
int a, k = 0;
ListNode l3 = new ListNode(-1), curr = l3;
do
{
if(k == 1)
a = l1.val + l2.val + 1;
else
a = l1.val + l2.val;
k = 0;
if(a >= 10){
curr.val = a - 10;
k = 1;
}
else
curr.val = a;
l1 = l1.next; l2 = l2.next;
curr.next = new ListNode(-1);
curr = curr.next;
}while(l1 != null && l2 != null);
return l3;
}
}
【问题讨论】:
-
为了澄清:您将两个数字中的每个数字表示为链表节点中的一个值,链表以“ones”值开头?所以你一个接一个地遍历这两个数字,“carry the one”?
标签: c# list variables linked-list