题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

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) {
        Stack<Integer> s1=new Stack<>();
        Stack<Integer> s2=new Stack<>();
        //将链表都加入到栈中
        while (head1!=null){
            s1.push(head1.val);
            head1=head1.next;
        }
        while (head2!=null){
            s2.push(head2.val);
            head2=head2.next;
        }
        int n1=0;
        int n2=0;
        int n=0;
        int ca=0;
        ListNode pre=null;
        ListNode node=null;
        //从栈中取出数据进行相加
        while (!s1.isEmpty() || !s2.isEmpty()) {
            n1=s1.isEmpty()?0:s1.pop();
            n2=s2.isEmpty()?0:s2.pop();
            n=n1+n2+ca;
            pre=node;
            node=new ListNode(n%10);
            node.next=pre;
            ca=n/10;
        }
        //说明有进位数
        if (ca>0){
            //有进位说明了要加一
            pre=node;
            node=new ListNode(ca);
            node.next=pre;
        }
        return  node;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-03 17:37
点赞 评论 收藏
分享
07-04 09:21
已编辑
Java
推拿大师:这是hr发的钓鱼贴吗
投递字节跳动等公司8个岗位
点赞 评论 收藏
分享
06-26 15:33
青岛工学院 Java
积极的秋田犬要冲国企:他现在邀请我明天面试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务