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

两个链表生成相加链表

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

反转链表或者栈的性质,栈结构真的好用!

import java.util.*;
public class Solution {
    //从后往前加,栈结构
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        Stack<ListNode> s1 = new Stack<>();
        Stack<ListNode> s2 = new Stack<>();
        int carry = 0;//进位

        while(head1!=null) {
            s1.push(head1);
            head1=head1.next;
        }

        while(head2!=null) {
            s2.push(head2);
            head2=head2.next;
        }

        while(!s1.isEmpty() || !s2.isEmpty() || carry!=0) {
            int x = s1.isEmpty() ? 0 : s1.pop().val;
            int y = s2.isEmpty() ? 0 : s2.pop().val;
            int sum = x + y + carry;
            carry = sum / 10;
            ListNode cur = new ListNode(sum%10);
            cur.next = head.next;
            head.next = cur;
        }
        return head.next;
}

结果用栈存储,计算结束后链接

import java.util.*;
public class Solution {
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    //从后往前加,栈结构
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        Stack<ListNode> s1 = new Stack<>();
        Stack<ListNode> s2 = new Stack<>();
        //栈存储结果,也可创建一个虚拟头结点,使用头插法;
        Stack<ListNode> res = new Stack<>();
        int carry = 0;//进位

        while(head1!=null) {
            s1.push(head1);
            head1=head1.next;
        }

        while(head2!=null) {
            s2.push(head2);
            head2=head2.next;
        }

        while(!s1.isEmpty() || !s2.isEmpty() || carry!=0) {
            int x = s1.isEmpty() ? 0 : s1.pop().val;
            int y = s2.isEmpty() ? 0 : s2.pop().val;
            int sum = x + y + carry;
            carry = sum / 10;
            res.push(new ListNode(sum%10));
        }
         ListNode head = res.isEmpty() ? null :res.pop(); 
         ListNode prev = head;
         while(!res.isEmpty()) {
             ListNode cur = res.pop();
             prev.next = cur;
             prev = prev.next;
         }
         return head;
    }
}
全部评论

相关推荐

07-03 11:02
中山大学 C++
字节刚oc,但距离九月秋招很近了有两段互联网实习,非腾讯字节。不敢赌转正,现在在纠结去还是不去如果实习俩月离职会有什么后果吗
阿城我会做到的:不去后悔一辈子,能否转正取决于ld的态度,只要他不卡,答辩就是走流程,个人觉得可以冲一把
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
05-24 14:12
门头沟学院 Java
点赞 评论 收藏
分享
头顶尖尖的程序员:我是26届的不太懂,25届不应该是找的正式工作吗?为什么还在找实习?大四还实习的话是为了能转正的的岗位吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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