Java for Leetcode 002 Add-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

Problem Solving Ideas:

Defines three listnode L1, L2,result, where result is the output of the return statement, L1, L2 is an incoming parameter.

Assign the L1 to result, execute result.val+=l2.val, and then L1 as the pointer level down until L2.NEXT is null. Of course, there will be a lot of boundary conditions, self-debug a bit better.

The Java code is as follows:

public class Solution {      static public ListNode addtwonumbers (listnode L1, ListNode L2) {    ListNode result=l1;    while (true) {    l1.val+=l2.val;    if (l1.val>=10) {    l1.val%=10;    if (l1.next==null) l1.next=new ListNode (1);    else l1.next.val+=1;    }    if (l2.next==null) {ListNode L3=l1.next;while (true) {if (l3==null) break;if (l3.val==10) {l3.val%=10;    if (l3.next==null) l3.next=new ListNode (1);    else l3.next.val+=1;} L3=l3.next;} break;}    L2=l2.next;    if (l1.next==null) {    l1.next=new listnode (0);    }    L1=l1.next;    }    return result;}        }

Java for Leetcode 002 Add-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.