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

链表相加(二)

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 reverseListNode(ListNode head) {
        ListNode pre = null, cur = head, nxt = null;
        while (cur != null) {
            nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }
        return pre;
    }

    //链表相加
    public ListNode addInList(ListNode head1, ListNode head2) {
        // write code here
        ListNode dummy = new ListNode(0);
        ListNode p = dummy;
        ListNode r1=reverseListNode(head1);
        ListNode r2=reverseListNode(head2);
        //进位
        int extra=0;
        while (r1!=null||r2!=null){
            int num1=r1==null?0:r1.val;
            int num2=r2==null?0:r2.val;
            int sum=num1+num2+extra;
            if(extra==1){
                //进位用过后归零
                extra=0;
            }
            extra+=(sum/10);
            ListNode newNode=new ListNode(sum%10);
            p.next=newNode;
            p=p.next;
            if(r1!=null){
                r1=r1.next;
            }
            if(r2!=null){
                r2=r2.next;
            }
        }
        if(extra>0){
            ListNode newNode=new ListNode(extra);
            p.next=newNode;
            p=p.next;
        }
        return reverseListNode(dummy.next);
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务