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

链表相加(二)

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类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        Stack<Integer> s1 = new Stack<>();
        Stack<Integer> s2 = new Stack<>();
        while(head1 != null){
            s1.push(head1.val);
            head1 = head1.next;
        }
        while(head2 != null){
            s2.push(head2.val);
            head2 = head2.next;
        }
        int count = 0;
        
        ListNode newNode = null;
        ListNode head = null;
        while(!s1.isEmpty() || !s2.isEmpty() || count==1){
            int a = (s1.isEmpty())?0:s1.pop();//逆序
            int b = (s2.isEmpty())?0:s2.pop();
            int sum = a + b + count;//模拟相加
            if(sum>9){
                count = 1;
                sum = sum%10;
            }
            else
                count = 0;
            //newNode.val = sum;
            newNode = new ListNode(sum);
            newNode.next = head;
            head = newNode;
           
        }
        return head;
   }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 14:35
点赞 评论 收藏
分享
醉蟀:你不干有的是人干
点赞 评论 收藏
分享
程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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