What is the LeetCode problem of adding two numbers in a linked list?

更新于
2026-10-12 11:42:02
1阅读来源:SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计194个文字,预计阅读时间需要1分钟。

What is the LeetCode problem of adding two numbers in a linked list?

javapublic static ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode result=new ListNode(0); int carry=0; ListNode current=result; while (l1 !=null || l2 !=null || carry !=0) { int l1Val=(l1 !=null) ? l1.val : 0; int l2Val=(l2 !=null) ? l2.val : 0; int sum=l1Val + l2Val + carry; carry=sum / 10; current.next=new ListNode(sum % 10); current=current.next; if (l1 !=null) l1=l1.next; if (l2 !=null) l2=l2.next; } return result.next;}

What is the LeetCode problem of adding two numbers in a linked list?

gistfile1.txt

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode result = new ListNode(0); int flow = 0; List res = new ArrayList (); while(l1!=null || l2!=null){ int l1Val = 0; int l2Val = 0; if(l1!=null){ l1Val = l1.val; } if(l2!=null){ l2Val = l2.val; } int curVal = l1Val + l2Val + flow > 10 ? (l1Val + l2Val + flow)/10: (l1Val + l2Val + flow)%10; int curFlow = l1Val + l2Val + flow >= 10?(l1Val + l2Val + flow)/10:0; flow = curFlow; l1 = l1.next; l2 = l2.next; res.add(curVal); } ListNode node = result; for(int i=0;i<=res.size()-2;i++){ node.val = res.get(i); node.next = new ListNode(res.get(i+1)); node = node.next; } return result; }

本文共计194个文字,预计阅读时间需要1分钟。

What is the LeetCode problem of adding two numbers in a linked list?

javapublic static ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode result=new ListNode(0); int carry=0; ListNode current=result; while (l1 !=null || l2 !=null || carry !=0) { int l1Val=(l1 !=null) ? l1.val : 0; int l2Val=(l2 !=null) ? l2.val : 0; int sum=l1Val + l2Val + carry; carry=sum / 10; current.next=new ListNode(sum % 10); current=current.next; if (l1 !=null) l1=l1.next; if (l2 !=null) l2=l2.next; } return result.next;}

What is the LeetCode problem of adding two numbers in a linked list?

gistfile1.txt

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode result = new ListNode(0); int flow = 0; List res = new ArrayList (); while(l1!=null || l2!=null){ int l1Val = 0; int l2Val = 0; if(l1!=null){ l1Val = l1.val; } if(l2!=null){ l2Val = l2.val; } int curVal = l1Val + l2Val + flow > 10 ? (l1Val + l2Val + flow)/10: (l1Val + l2Val + flow)%10; int curFlow = l1Val + l2Val + flow >= 10?(l1Val + l2Val + flow)/10:0; flow = curFlow; l1 = l1.next; l2 = l2.next; res.add(curVal); } ListNode node = result; for(int i=0;i<=res.size()-2;i++){ node.val = res.get(i); node.next = new ListNode(res.get(i+1)); node = node.next; } return result; }