java 栈+链表头插法

两个链表生成相加链表

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

可惜只能过 75% orz

public static ListNode addInList (ListNode head1, ListNode head2) {
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        ListNode p1 = head1;
        ListNode p2 = head2;
        while (p1 != null) {
            stack1.add(p1.val);
            p1 = p1.next;
        }
        while (p2 != null) {
            stack2.add(p2.val);
            p2 = p2.next;
        }
        ListNode head = new ListNode(-1);
        int temp = 0;
        while (!stack1.isEmpty() || !stack2.isEmpty() || temp!=0) {
            int num1 = stack1.isEmpty() ? 0 : stack1.pop();
            int num2 = stack2.isEmpty() ? 0 : stack2.pop();
            int sum = (num1+num2+temp)%10;
            temp = (num1+num2+temp)/10;
            ListNode next = head.next;
            ListNode node = new ListNode(sum);
            head.next = node;
            node.next = next;
        }
        return head.next;
    }
全部评论

相关推荐

10-17 16:07
门头沟学院 Java
牛牛大你18号:在汇报,突然弹出来,,领导以为我在准备跳槽,刚从领导办公室谈心出来
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务