每天一道算法题之两数相加II

两数相加II

题目描述:

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。你可以假设除了数字 0 之外,这两个数字都不会以零开头。1

  • 例如:

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

  • 题目解析:

    • 链表存储的数据是从高位开始存储,在计算时需要进行处理(用栈存储元素,栈是先进后出).
    • 结果输出也是从高位开始,用栈暂时先存储结果.
    • 考虑计算时链表长度分为三部分:
      • 当前位置链表均非null
      • 当前位置有一个非null
      • 当前位置另一个非null
    • 处理进位

    代码部分:

  public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
      //借助栈求解
      if(l1 == null && l2 != null) return l2;
      if(l1 != null && l2 == null) return l1;
      if(l1 == null && l2 == null) return null;
  
      Stack<Integer> stack1 = new Stack<Integer>();
      Stack<Integer> stack2 = new Stack<Integer>();
      Stack<Integer> stack3 = new Stack<Integer>();
      
      //数据入栈操作
      ListNode temp1 = l1;
      ListNode temp2 = l2;
      while(temp1 != null){
          stack1.push(temp1.val);
          temp1 = temp1.next;
      }
      while(temp2 != null){
          stack2.push(temp2.val);
          temp2 = temp2.next;
      }
      //开始运算
      int sol = 0;//进位
      
      while((!stack1.isEmpty()) && (!stack2.isEmpty())){
          int num1 = stack1.pop();
          int num2 = stack2.pop();
          int res = num1 + num2 + sol;
          sol = res / 10;
          stack3.push(res%10);
      }
      
      while(!stack1.isEmpty()){
          int num1 = stack1.pop();
          int res = num1 + sol;
          sol = res / 10;
          stack3.push(res%10);
      }
      
      while(!stack2.isEmpty()){
          int num2 = stack2.pop();
          int res = num2 + sol;
          sol = res / 10;
          stack3.push(res%10);
      }
      
      if(sol != 0) stack3.push(sol);
  
      ListNode res = new ListNode(0);
      ListNode temp3 = res;
      
      while(!stack3.isEmpty()){
          temp3.next = new ListNode(stack3.pop());
          temp3 = temp3.next;
      }
      
      return res.next;
  }

  1. https://leetcode-cn.com/problems/add-two-numbers-ii/ ↩︎

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值