题解 | #两个链表生成相加链表#

两个链表生成相加链表

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

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    private ListNode reverse(ListNode head)
    {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null)
        {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        Stack<ListNode> stack1 = new Stack<>();
        Stack<ListNode> stack2 = new Stack<>();
        while (head1 != null)
        {
            stack1.push(head1);
            head1 = head1.next;
        }
        while (head2 != null)
        {
            stack2.push(head2);
            head2 = head2.next;
        }
        ListNode result = new ListNode(0);
        ListNode curr = result;
        int sum = 0;
        while (!stack1.isEmpty() || !stack2.isEmpty())
        {
            if (!stack1.isEmpty())
            {
                sum += stack1.pop().val;
            }
            if (!stack2.isEmpty())
            {
                sum += stack2.pop().val;
            }
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
            sum = sum >= 10 ? 1 : 0;
        }
        // 这里容易忘记
        if (sum > 0)
        {
            curr.next = new ListNode(sum);
        }
        return reverse(result.next);
    }
}
全部评论

相关推荐

10-07 20:48
门头沟学院 Java
听说改名就会有offer:可能是实习上着班想到后面还要回学校给导师做牛马,看着身边都是21-25的年纪,突然emo了了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务