Add Two Numbers

来源:互联网 发布:网络科技部个体户名称 编辑:程序博客网 时间:2024/06/05 13:35

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8


思路:

首先明白题目是什么意思,就是一个数用链表存储,头节点存储个位,第二个节点存储十位,依次类推。现在有两个数用链表表示,将它们求和,返回和的链表表示形式。做过plus one这道题的话,应该思路很清晰的,注意进位即可。另外,新的数最好构造一个新的链表来存储,使用原两个链表中的一个来存储会比较麻烦,因为两个链表长度可能会不一样,当一方为null后,需要更改另一链表节点的指向。当两链表均搜索到末尾元素之后,还需要判断是否有进位的情况。


class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {         ListNode a1 = l1;         ListNode a2 = l2;         ListNode dummy = new ListNode(0);         ListNode cur = dummy;         int sum = 0;         while(a1 != null || a2 != null) {         sum /= 10;         if(a1 != null) {         sum += a1.val;         a1 = a1.next;         }         if(a2 != null) {         sum += a2.val;         a2 = a2.next;         }         cur.next = new ListNode(sum%10);         cur = cur.next;         }         if(sum/10 == 1) {         cur.next = new ListNode(1);         }         return dummy.next;    }}



原创粉丝点击