Add Two Numbers

来源:互联网 发布:工资数据分析表 编辑:程序博客网 时间:2024/05/17 04:07

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

解题思路:按照位数读下去,维护当前位和进位,时间复杂度是O(n),空间复杂度是O(1)。

package edu.bit.leetcode;public class AddTwoNumbers {    public static ListNode init_listnode1() {        ListNode head = new ListNode(2);        ListNode node1 = new ListNode(4);        ListNode node2 = new ListNode(3);        head.next = node1;        node1.next = node2;        return head;    }    public static ListNode init_listnode2() {        ListNode head = new ListNode(5);        ListNode node1 = new ListNode(6);        ListNode node2 = new ListNode(4);        ListNode node3 = new ListNode(2);        head.next = node1;        node1.next = node2;        node2.next = node3;        return head;    }    public static void printList(ListNode head) {        ListNode current = head;        while(current != null) {            System.out.print(current.val + " ");            current = current.next;        }    }    public static ListNode add_two_sum(ListNode head1, ListNode head2) {        if(head1 == null && head2 == null) {            return null;        }        ListNode head = null;        ListNode current = null;        int carry = 0;        while(head1 != null && head2 != null) {            int sum = carry + head1.val + head2.val;            ListNode point = new ListNode(sum%10);            carry = sum / 10;            if (head == null) {                head = point;                current = head;                current.next = null;            } else {                current.next = point;                current = current.next;            }            head1 = head1.next;            head2 = head2.next;        }        while(head1 != null) {            int sum = carry + head1.val;            current.next = new ListNode(sum%10);            carry = sum / 10;            head1 = head1.next;            current = current.next;        }        while(head2 != null) {            int sum = carry + head2.val;            current.next = new ListNode(sum%10);            carry = sum / 10;            head2 = head2.next;            current = current.next;        }        return head;    }    public static void main(String[] args) {        ListNode head1 = init_listnode1();        ListNode head2 = init_listnode2();        ListNode result = add_two_sum(head1,head2);        printList(result);    }}class ListNode {    int val;    ListNode next;    ListNode(int val) {        this.val = val;        this.next = null;    }}
0 0