Problem Description:
You are given, linked lists representing, and non-negative numbers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.
Input: (2, 4, 3) + (5, 6, 4)
Output: 7, 0, 8
Problem Solving Ideas:
Set up a head listnode and tail listnode, two lists start from the beginning, 22 add and set the carry carry, if the sum of more than 10 carry 1, otherwise zero. At the same time, consider a list and the length, the other end of the situation.
The code is as follows:
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {7 * val = x;8 * next = null;9 * }Ten * } One */ A Public classSolution { - PublicListNode addtwonumbers (listnode L1, ListNode L2) { - theListNode head =NewListNode (0); -ListNode tail =head; - intsum = 0; - intCarry = 0; + - while(L1! =NULL|| L2! =NULL){ + if(L1 = =NULL){ Asum = L2.val +carry; atL2 =L2.next; - } - Else if(L2 = =NULL){ -sum = L1.val +carry; -L1 =L1.next; - } in Else{ -sum = l1.val + L2.val +carry; toL1 =L1.next; +L2 =L2.next; - } the * if(Sum >= 10){ $carry = SUM/10;Panax Notoginsengsum = sum% 10; - } the Else{ +Carry = 0; A } the +Tail.next =Newlistnode (sum); -Tail =Tail.next; $ } $ - if(Carry! = 0){ -Tail.next =NewListNode (carry); theTail =Tail.next; - }Wuyi the returnHead.next; - } Wu}
Java [Leetcode 2] Add Numbers