美文网首页
LeetCode - 2

LeetCode - 2

作者: DevWang | 来源:发表于2018-01-02 11:20 被阅读0次

Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.




















思路

  • 从头节点开始遍历这两个链表,将每一个对应节点进行相加,结果再除以10作为下一位相加的进位,同时记录余数作为本位的结果,一直处理,直到所有的结点都处理完;

  • 当两个链表都到末尾时,判断当前进位是否为1,是的话则增加新节点,值为1;否则直接返回结果;

  • 当其中一个链表未到末尾时,将新链表尾部next指向此链表的next位置,并判断进位是否为1,为1的话则执行类似第一步的操作,直到进行为0,返回结果.

  • 实现代码:

    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }
    }
    
    public ListNode addTwoNumbers(ListNode head1, ListNode head2) {
        if(null == head1 || null == head2) {
            return null;
        }
        ListNode head = new ListNode(0); // 建立新链表的头节点
        ListNode result = head;
        int carry = 0; // 进位,值为 1 或 0
        while (head1.next != null && head2.next != null) {
            head1 = head1.next;
            head2 = head2.next;
            int val = (head1.val + head2.val + carry) % 10;
            carry = (head1.val + head2.val + carry) / 10;
            head.next = new ListNode(val);
            head = head.next;
        }
        if (head1.next != null) { // 链表1未结束
            head.next = head1.next;
        } else if (head2.next != null) { // 链表2未结束
            head.next = head2.next;
        }
    
        if (carry == 1) { // 有进位则继续遍历链表
            while (head.next != null) {
                head = head.next;
                int temp = head.val + carry;
                head.val = temp % 10;
                carry = temp / 10;
            }
            if (carry == 1) {
                head.next = new ListNode(1);
            }
        }
        return result;
    }

相关文章

网友评论

      本文标题:LeetCode - 2

      本文链接:https://www.haomeiwen.com/subject/uzsfnxtx.html