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

链表相加(二)

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 static ListNode reverse(ListNode node){
        ListNode pre = null;
        ListNode next = null;
        
        while(node!=null){
            next = node.next;
            node.next=pre;
            pre = node;
            node = next;
        }
        return pre;
    }
    
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        ListNode l1 = reverse(head1);
        ListNode l2 = reverse(head2);
        
        Stack<Integer> s = new Stack<>();
        
        int j = 0;
        int sum = 0;
        while(l1!=null||l2!=null){
            if(l1!=null){
                sum=sum+l1.val;
                l1=l1.next;
            }
            if(l2!=null){
                sum=sum+l2.val;
                l2=l2.next;
            }
            sum=sum+j;
            int res = sum%10;
            s.add(res);    
            if(sum>=10){
                j=1;
            }else{
                j=0;
            }  
            sum=0;
        }
        if(j==1){
            s.add(1);
        }
        
        ListNode head;
        ListNode node = new ListNode(s.pop());
        head = node;
        while(!s.isEmpty()){
            ListNode nextnode = new ListNode(s.pop());
            node.next=nextnode;
            node = node.next;
        }
        
        return head;

    }
}
全部评论

相关推荐

07-01 19:00
门头沟学院 Java
点赞 评论 收藏
分享
05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
自由水:笑死了,敢这么面试不敢让别人说
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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