Problem description
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.
Input & Output
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Code
/**
* 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 res = new ListNode(0);
ListNode p = l1;
ListNode q = l2;
ListNode curr = res;
int flag = 0;
while(q != null && p != null) {
ListNode temp = new ListNode((p.val + q.val + flag) % 10);
curr.next = temp;
curr = temp;
flag = (p.val + q.val + flag) / 10;
q = q.next;
p = p.next;
}
while(p != null) {
ListNode temp = new ListNode((p.val + flag) % 10);
curr.next = temp;
curr = temp;
flag = (p.val + flag) / 10;
p = p.next;
}
while(q != null) {
ListNode temp = new ListNode((q.val + flag) % 10);
curr.next = temp;
curr = temp;
flag = (q.val + flag) / 10;
q = q.next;
}
if(flag != 0) {
ListNode temp = new ListNode(flag);
curr.next = temp;
curr = temp;
}
return res.next;
}
}
Analysis
- 注意链表的建立过程。
网友评论