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
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {val = x;}}} */public class Soluti On {public ListNode addtwonumbers (listnode L1, ListNode L2) {if (L1 = = null) return l2;if (L2 = null) It looks simple, but it takes a long time, the list has to be traversed a few times, but the code is the shortest? I really don't want to write return l1;int temp = 0; ListNode p = L1; ListNode q = L2; ListNode longlist = L1; ListNode la = L1;while (P! = NULL && Q! = null) {p = P.next;q = Q.next;} if (q = = null) {q = l1;p = L2;longlist = L1;} else {q = l2;p = L1;longlist = L2;} while (P! = NULL && Q! = null) {if (p.val + q.val + temp >=) {q.val = P.val + q.val + temp-10;temp = 1;} E LSE {Q.val = Q.val + p.val + temp;temp = 0;} p = p.next;q = Q.next;} while (q = null) {if (Q.val + temp >=) {q.val = q.val + temp-10;temp = 1;} else {q.val = q.val + temp;temp = 0;} Q = Q.next;} if (temp = = 1) {ListNode last = new ListNode (1); last.next = Null;p = Longlist;while (p.next!= null) p =P.next;la = P;la.next = Last;} return longlist; }}
(Linked list) 2. Add the Numbers