反转链表后再相加

两个链表生成相加链表

http://www.nowcoder.com/questionTerminal/c56f6c70fb3f4849bc56e33ff2a50b6b

public class Solution {
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        head1 = reverse(head1);
        head2 = reverse(head2);
        ListNode head = new ListNode(-1);
        ListNode cur = head;
        int carry = 0;
        while(head1 != null || head2 != null) {
            int val = carry;
            if (head1 != null) {
                val += head1.val;
                head1 = head1.next;
            }
            if (head2 != null) {
                val += head2.val;
                head2 = head2.next;
            }
            cur.next = new ListNode(val % 10);
            carry = val / 10;
            cur = cur.next;
        }
        if (carry > 0) {
            cur.next = new ListNode(carry);
        }
        return reverse(head.next);
    }

    private ListNode reverse(ListNode head) {
        ListNode cur = head;
        ListNode pre = null;
        while(cur != null) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
}
全部评论
好家伙,一模一样的思路
1 回复 分享
发布于 2020-12-08 13:58
经典,我就只想得到入栈。。。
点赞 回复 分享
发布于 2021-09-07 14:18
if (carry > 0) cur.next = new ListNode(carry);这边应该是cur = new ListNode(carry)才对吧
点赞 回复 分享
发布于 2021-07-11 22:10

相关推荐

10-20 15:26
门头沟学院 Java
桥头牛油火锅:这个比例不正常,简历的话项目经历放中间,项目功能分点可以再明确点,前面加“·”或者“1 2 3”,另外简历上的照片可以去外面摄影店拍一下,以后也会用到的,hr筛人也是多少会看的,毕竟世界是一个巨大的卡颜局嘛,还有有些hr由于消息太多可能没看到,后面可能会回来找你,要简历的还会多一点,我也是普2本,比例大致是600:90:15:3,当然我实力不太够,拿的offer比较少,慢慢来吧
点赞 评论 收藏
分享
评论
19
1
分享

创作者周榜

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