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

链表相加(二)

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;
    }

}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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