LeetCode 445. 两数相加 II

题目

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。

将这两数相加会返回一个新的链表。你可以假设除了数字 0 之外,这两个数字都不会以零开头。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers-ii

示例

输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7

思路:将两个链表存入到栈中,同时pop相加,并且进位用变量存储起来

反转问题首先想到的是栈

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> s1 = new Stack<>();
        Stack<Integer> s2 = new Stack<>();

        while(l1 != null){
            s1.push(l1.val);
            l1 = l1.next;
        }
        while(l2 != null){
            s2.push(l2.val);
            l2 = l2.next;
        }
        ListNode head = null;
        int point = 0;  //来标志进位
        while(!s1.isEmpty() || !s2.isEmpty() || point > 0){
            int sum = point;
            sum += s1.isEmpty() ? 0:s1.pop();
            sum += s2.isEmpty() ? 0:s2.pop();
            ListNode tmp = new ListNode(sum % 10);
            tmp.next = head;       //将头指针与这个值相连
            head = tmp;         //头指针与node一起指向一个节点
            point = sum/10;       //如果有进位那么就保存在point里面
        }
        return head;
        
    }
}

大家如果感兴趣可以前去手搓

本分类只用作个人记录,大佬轻喷.

原文地址:https://www.cnblogs.com/xiaofff/p/12699413.html