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

链表相加(二)

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) {
        // write code here
           // 定一个临时链表
        ListNode temp = new ListNode(-1);
        head1 = reversalList(head1);
        head2 = reversalList(head2);
        // 尾节点
        ListNode tempTail = temp;
        // 临时个位置
        int res = 0;
        while(head1 != null || head2 != null) {
            int sum = res;
            if (head1 != null) {
                sum = sum + head1.val;
                head1 = head1.next;
            }
            if (head2 != null) {
                sum = sum + head2.val;
                head2 = head2.next;
            }
            res = sum / 10;
            int val = sum % 10;
            ListNode node = new ListNode(val);
            tempTail.next = node;
            tempTail = tempTail.next;

        }
        if (res > 0) {
            ListNode node = new ListNode(res);
            tempTail.next = node;
        }
        return reversalList(temp.next);
    }

    public ListNode reversalList(ListNode head) {
        // 定一个栈, 将head1进行反转
        Stack<ListNode> stack = new Stack<>();
        while (head != null) {
            stack.push(head);
            head = head.next;
        }
        // 出栈
        head = stack.pop();
        ListNode cur = head;
        while (!stack.isEmpty()) {
            ListNode node = stack.pop();
            node.next = null;
            cur.next = node;
            cur = cur.next;
        }
        return head;
    }
}

全部评论

相关推荐

昨天 12:24
重庆大学 运营
坏消息:和好工作擦肩而过
给点吧求求了:怎么可能因为差几秒,估计就是简历更好看婉拒了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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