题目:两个链表存储数字,然后求和,和值存储在一个链表中。
代码:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode result = head; int carry = 0 , tempSum = 0;
while(l1 != null || l2 != null){
int v1 , v2;
v1 = (l1 != null) ? l1.val : 0;
v2 = (l2 != null) ? l2.val : 0;
tempSum = v1 + v2 + carry;
carry = tempSum / 10;
tempSum = tempSum % 10;
head.next = new ListNode(tempSum);
head = head.next; l1 = (l1 != null) ? l1.next : null;
l2 = (l2 != null) ? l2.next : null;
} if(carry > 0) head.next = new ListNode(carry); return result.next;
}