【每日一题】【栈】2022年2月2日-NC40 两个链表生成相加链表

描述

假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。

 

答案:栈

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        ListNode head = new ListNode(-1);
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        while(head1 != null) {
            stack1.push(head1.val);
            head1 = head1.next;
        }
        while(head2 != null) {
            stack2.push(head2.val);
            head2 = head2.next;
        }
        int carry = 0;
        while(!stack1.isEmpty() && !stack2.isEmpty()) {
            int val = stack1.pop() + stack2.pop() + carry;
            int num = val % 10;
            carry = val / 10;
            ListNode node = new ListNode(num);
            node.next = head.next;
            head.next = node;
        }
        while(!stack1.isEmpty()) {
            int val = stack1.pop() + carry;
            int num = val % 10;
            carry = val / 10;
            ListNode node = new ListNode(num);
            node.next = head.next;
            head.next = node;
        }
        while(!stack2.isEmpty()) {
            int val = stack2.pop() + carry;
            int num = val % 10;
            carry = val / 10;
            ListNode node = new ListNode(num);
            node.next = head.next;
            head.next = node;
        }
        if(carry != 0) {
            ListNode node = new ListNode(carry);
            node.next = head.next;
            head.next = node;
        }
        return head.next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值