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

链表相加(二)

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

本题与剑指offer 大数相加算法相似,步骤都是 1.对齐 2.从个位开始相加,也就是需要从后向前处理 链表中,从后向前,需要先反转链表;

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
        //反转两个链表
        ListNode newHead1 = reveseList(head1);
        ListNode newHead2 = reveseList(head2);
        ListNode result = null;
        //记录进位
        int flag = 0;
        //从后往前相加
        while (newHead1 != null || newHead2!=null){
            int a = newHead1 == null?0:newHead1.val;
            int b = newHead2 == null?0:newHead2.val;
          //在拼接结果链表时,将最新节点指向上一个节点
            ListNode cur = new ListNode((a+b+flag)%10);
            cur.next = result;
            result = cur;
            flag = (a+b+flag)/10;
            newHead1 = newHead1 == null?null:newHead1.next;
            newHead2 = newHead2 == null?null:newHead2.next;
            if (newHead2 == null && newHead1 == null && flag != 0){
                cur = new ListNode(1);
                cur.next = result;
                result = cur;
            }
        }

        return result;
    }
    //反转链表
    private ListNode reveseList(ListNode head){
        if (head == null){
            return null;
        }
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = null;
        while (cur != null){
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}
全部评论

相关推荐

10-25 00:32
香梨想要offer:感觉考研以后好好学 后面能乱杀,目前这简历有点难
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务