题解 | #链表相加(二)#
链表相加(二)
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 reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        if (head1 == null) return head2;
        if (head2 == null) return head1;
        int flag = 0;
        ListNode h1 = reverseList(head1);
        ListNode h2 = reverseList(head2);
        ListNode h3 = new ListNode(-1);
        ListNode h33 = h3;
        while (h1 != null && h2 != null) {
            int curnums = h1.val + h2.val + flag;
            int curnum = curnums % 10;
            flag = curnums / 10;
            ListNode cur = new ListNode(curnum);
            h3.next = cur;
            h3 = cur;
            h1=h1.next;
            h2=h2.next;
        }
        while (h1 != null) {
            int curnums = h1.val + flag;
            int curnum = curnums % 10;
            flag = curnums / 10;
            ListNode cur = new ListNode(curnum);
            h3.next = cur;
            h3 = cur;
            h1=h1.next;
        }
        while (h2 != null) {
            int curnums = h2.val + flag;
            int curnum = curnums % 10;
            flag = curnums / 10;
            ListNode cur = new ListNode(curnum);
            h3.next = cur;
            h3 = cur;
            h2=h2.next;
        }
        if (flag == 1) {
            ListNode cur = new ListNode(1);
            h3.next = cur;
            h3 = cur;
        }
        ListNode res = reverseList(h33.next);
        return res;
    }
}
基恩士成长空间 421人发布
查看11道真题和解析