题解 | #链表相加(二)#

链表相加(二)

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

import java.util.*;

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

public class Solution {
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    private int add = 0;
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        // 要么用栈进行 头插法
        // 要么递归进行!
        // 因为不确定到底那个链表更长所以就不递归了!
        Deque<ListNode> stack1 = new LinkedList<>();
        Deque<ListNode> stack2 = new LinkedList<>();
        
        while(head1 != null){
            stack1.push(head1);
            head1 = head1.next;
        }
        
        while(head2 != null){
            stack2.push(head2);
            head2 = head2.next;
        }
        
        ListNode fake_head = new ListNode(-1);
        ListNode tail = fake_head.next;
        
        int add = 0;
        while( !stack1.isEmpty() && !stack2.isEmpty()){
            int val = stack1.pop().val + stack2.pop().val + add;
            add = val / 10;
            ListNode node = new ListNode(val%10);
            node.next = tail;
            fake_head.next = node;
            tail = node;
        }
        
        while(!stack1.isEmpty()){
            int val  = stack1.pop().val + add;
            add = val /10;
            ListNode node = new ListNode(val%10);
            node.next = tail;
            fake_head.next = node;
            tail = node;
        }
        
         while(!stack2.isEmpty()){
            int val  = stack2.pop().val + add;
            add = val/10;
            ListNode node = new ListNode(val%10);
            node.next = tail;
            fake_head.next = node;
            tail = node;
        }
            
         if(add != 0) {
            ListNode node = new ListNode(add);
            node.next = tail;
            fake_head.next = node;
            tail = node;
         }
        return fake_head.next;
    }
}
全部评论

相关推荐

程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
下北澤大天使:你是我见过最美的牛客女孩😍
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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