(Linked list) 2. Add the Numbers

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.