LeetCode 2. Add Two Numbers
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
【题目分析】
用两个链表来表示两个非负数的逆序拍列,每个节点包含一个数字。例如:2 -> 4 -> 3代表342,5 -> 6 -> 4代表465,342+465 = 807。求这两个数的和,并用同样的方式返回。
【思路】
两数按位相加,只要处理好向后进位即可。当前相加结果 = 链表1数字+链表2数字+前一个进位。
【java代码】
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 11 if(l1==null) return l2; 12 if(l2==null) return l1; 13 14 ListNode l3 = new ListNode(0); 15 ListNode tail = l3; 16 17 int flag = 0; 18 while(l1!=null || l2!=null){ 19 int num1 = 0, num2 = 0; 20 if(l1 != null){ 21 num1 = l1.val; 22 l1 = l1.next; 23 } 24 if(l2 != null){ 25 num2 = l2.val; 26 l2 = l2.next; 27 } 28 int num = num1 + num2 + flag; 29 flag = num / 10; 30 num = num % 10; 31 ListNode node = new ListNode(num); 32 tail.next = node; 33 tail = node; 34 } 35 if(flag == 1){ 36 ListNode node = new ListNode(1); 37 tail.next = node; 38 tail = node; 39 } 40 tail.next = null; 41 return l3.next; 42 } 43 }