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

两个链表生成相加链表

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
        if(head1==null) return head2;
        if(head2==null) return head1;
        ListNode newHead1  = reverse(head1);
        ListNode newHead2  = reverse(head2);
//         Deque<Integer> stack1 = new LinkedList<>();
//         Deque<Integer> stack2 = new LinkedList<>();
//         while(head1 != null){
//             stack1.push(head1.val);
//             head1 = head1.next;
//         }
//         while(head2 != null){
//             stack2.push(head2.val);
//             head2 = head2.next;
//         }
        int jin = 0 , yushu = 0 ;
        ListNode tmp = new ListNode(-1);
        ListNode head = tmp;
        while(newHead1 != null || newHead2 != null){
            int value1 = newHead1 == null ? 0 : newHead1.val;
            int value2 = newHead2 == null ? 0 : newHead2.val;
            yushu = (value1 + value2 + jin)%10;
            jin = (value1 + value2 + jin)/10;
            tmp.next = new ListNode(yushu);
            tmp = tmp.next;
            if(newHead1 != null){newHead1 = newHead1.next;}
            if(newHead2 != null){newHead2 = newHead2.next;}
        }

        if(jin != 0){
            tmp.next = new ListNode(jin);
        }

        return reverse(head.next);
    }
    public ListNode reverse(ListNode head){
        ListNode pre = null,cur = head, nxt = head;
        while(cur!=null){
            nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }
        return pre;
    }
}
全部评论

相关推荐

10-09 22:05
666 C++
找到工作就狠狠玩CSGO:报联合国演讲,报电子烟设计与制造
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务