链表相加
/**
* 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; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode();
ListNode cur = head;
int leftValue = 0;
while(l1!=null||l2!=null||leftValue!=0){
if(l1!=null){
leftValue+=l1.val;
l1 = l1.next;
}
if(l2!=null){
leftValue+=l2.val;
l2 = l2.next;
}
cur.next = new ListNode(leftValue%10);
cur = cur.next;
leftValue /=10;
}
return head.next;
}
}
该博客介绍了一个使用链表表示数字的方法,并展示了如何实现将两个链表表示的数字相加的算法。通过迭代处理每个节点,累加对应的数值并处理进位,最后得到结果链表。

被折叠的 条评论
为什么被折叠?



