码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 两个单链表两数相加

时间:2021-06-02 16:21:23      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:null   sum   return   链表   linked   res   ati   ||   targe   

题目

package whale.leetcode.simple;

/**
 * @Author: WhaleFall541
 * @Date: 2021/5/29 20:30
 */
public class AddTwoSumLinkedList {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /*
    [9,9,9,9,9,9,9]
    [9,9,9,9]
     */
    public static void main(String[] args) {
        ListNode l1 = new ListNode(9, new ListNode(9, new ListNode(9,
                new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))))));
        ListNode l2 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))));
        ListNode result = addTwoNumbers(l1, l2);
        while (result != null) {
            System.out.println(result.val);
            result = result.next;
        }

    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result;
        ListNode head = result = new ListNode();
        int temp=0, value1, value2;

        while (l1 != null || l2 != null) {
            value1 = (l1 == null) ? 0 : l1.val;
            value2 = (l2 == null) ? 0 : l2.val;

            // 当前指针位值的值相加
            result.val = value1 + value2 + temp;
            // 进位每次加完就置为0
            temp = 0;
            if (result.val > 9) {
                temp = result.val / 10;// 记录进位的值
                result.val = result.val % 10;// 记录当前位的值
            }
            // l1 l2 只要不为空则后移指针
            if (l1 != null)
                l1 = l1.next;
            if (l2 != null)
                l2 = l2.next;
            // l1 l2 只要其一不为空则结果集需要后延一位
            if (l1 != null || l2 != null)
                result = result.next = new ListNode();
        }

        if (temp!=0)
            result.next = new ListNode(temp);
        return head;
    }
}

leetcode 两个单链表两数相加

标签:null   sum   return   链表   linked   res   ati   ||   targe   

原文地址:https://www.cnblogs.com/whalefall541/p/14826519.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!