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

两个链表生成相加链表

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

相关推荐

05-30 12:03
山西大学 C++
offer来了我跪着接:不是骗子,等到测评那一步就知道为啥这么高工资了
点赞 评论 收藏
分享
把实习生当正职使昨天第一天就加班,晚上连口饭都没吃上,以后日子咋过,我不想干了
码农索隆:实习不怕忙,就怕干的活重复且没难度,要干就干那种有深度有难度的任务,这样才能快速的提升
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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