2. Add Two Numbers

来源:互联网 发布:ubuntu下载qq 编辑:程序博客网 时间:2024/06/13 01:49

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

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {                ListNode result = new ListNode(0);        ListNode first = result;        int high = 0;        int current = 0;        int l1num,l2num;                while(l1!=null||l2!=null||high==1)        {            l1num = l1!=null?l1.val:0;            l2num = l2!=null?l2.val:0;            current = (l1num+l2num+high);            if(current >= 10)            {                high = 1;                current -=10;            }            else                high = 0;                        ListNode temp = new ListNode(current);                        result.next = temp;            result = temp;                        if(l1!=null)                l1 = l1.next;            if(l2!=null)                l2 = l2.next;           // result = temp.next;        }                return first.next;            }}


0 0