2.Add Two Numbers
原题
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
解决
方法1:模拟加法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//主要考察的是链表的操作。
ListNode dummyHead = new ListNode(-1);
ListNode res = dummyHead;
ListNode p1 = l1, p2 = l2;
int carry = 0;
while(p1 != null || p2 != null) {
int v1 = p1 == null? 0 : p1.val;
int v2 = p2 == null? 0 : p2.val;
int r = v1 + v2 + carry;
//需要进位
carry = r / 10;
//赋值
res.next = new ListNode(r % 10);
res = res.next;
if(p1 != null) p1 = p1.next;
if(p2 != null) p2 = p2.next;
}
//判断是否还要进位
if(carry != 0) res.next = new ListNode(carry);
return dummyHead.next;
}
}