题解 | 链表相加(二)

链表相加(二)

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

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        if (head1 == null) return head2;
        if (head2 == null) return head1;
        int mark = 0;
        ListNode phead1=reverNode(head1);
        ListNode phead2 = reverNode(head2);
        ListNode res = new ListNode(-1);
        ListNode head = res;
        while(phead1!=null||phead2!=null||mark>0){
            int res1 = phead1==null?0:phead1.val;
            int res2 = phead2==null?0:phead2.val;
            int temp = res1+res2+mark;
            mark = temp/10;
            temp = temp%10;
            head.next = new ListNode(temp);
            head = head.next;
            if(phead1!=null) phead1=phead1.next;
            if(phead2!=null) phead2=phead2.next;
        }
        return reverNode(res.next);
    }
    /**
    反转链表
     */
    public ListNode reverNode(ListNode head){
        if(head==null){
            return head;
        }
        ListNode pre = null;
        ListNode cur = head;
        while(cur!=null){
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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