• 主页

# (oJ)链表非负整型数据相加问题,oj判断我时间超时，帮忙分析一下,谢谢！！

``````
/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int c=0;
ListNode temp1=l1,temp2=l2,temp,sum=new ListNode(0);
ListNode Sum=sum;

while(temp1!=null&&temp2!=null)
{
temp=new ListNode((c+temp1.val+temp2.val)%10);
c=(c+temp1.val+temp2.val)/10;
sum.next=temp;sum=temp;
temp1=temp1.next;temp2=temp2.next;
}

while(temp1!=null)
{
temp=new ListNode((c+temp1.val)%10);
c=(c+temp1.val)/10;
sum.next=temp;sum=temp;
}

while(temp2!=null)
{
temp=new ListNode((c+temp2.val)%10);
c=(c+temp2.val)/10;
sum.next=temp;sum=temp;
}
if(c!=0)
{
temp=new ListNode(c);
sum.next=temp;
}
return Sum.next;
}
``````

oj提供的答案：
``````
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
}
``````
...全文
86 点赞 收藏 3

3 条回复

Java SE

3.4w+

30.7w+

Java 2 Standard Edition