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;
    }
全部评论

相关推荐

04-27 08:59
常州大学 Java
牛客139242382号:《两门以上汇编语言》
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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