LeetCode——Add Two Numbers

来源:互联网 发布:淘宝桔子表行靠谱不 编辑:程序博客网 时间:2024/05/22 12:18

题目描述如下:

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

/** * @author moming * @since  JDK1.7 */class Solution {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {if (l1 == null)return l2;if (l2 == null)return l1;//ret: 结果存于l1中//prel:用于有进位时创建新nodeListNode ret = l1;ListNode prel = new ListNode(0);prel.next = l1;int flag = 0;while (l1 != null && l2 != null) {l1.val = l1.val + l2.val + flag;flag = l1.val / 10;l1.val = l1.val % 10;prel = l1;l1 = l1.next;l2 = l2.next;}if (l2 != null) {l1 = l2;prel.next = l1;}while (l1 != null) {l1.val += flag;flag = l1.val / 10;l1.val %= 10;prel = l1;l1 = l1.next;}if(flag == 1){ListNode node = new ListNode(1);prel.next = node;}return ret;}}





0 0