给定两个非空链表,数字以相反的顺序存储,每个节点都包含一个数字。将相同位置数字相加,并将其作为链接列表返回。
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
解法一:
package com.lipeng.leetcode;
/**
* 实现思路:
* 直接将两个链表相同位置的数字相加,但因为数组顺序是反的,所以当前节点大于10时,应该进位到下两个节点之和上
* 使用sumVal保存相同位置数字之和,isPlus保存应该进位的数字,nodeVal存储当前Node的val。
* sumVal=node1.val+node2.val;
* isPlus=sumVal/10;
* nodeVal=sumVal%10;
* @author LiPeng
* @date 2018年1月24日
*/
public class AddTwoNumbersLc {
public static void main(String[] args) {
ListNode l1_1=new ListNode(2);
ListNode l1_2=new ListNode(4);
ListNode l1_3=new ListNode(3);
l1_1.next=l1_2;
l1_2.next=l1_3;
ListNode l2_1=new ListNode(5);
ListNode l2_2=new ListNode(6);
ListNode l2_3=new ListNode(4);
l2_1.next=l2_2;
l2_2.next=l2_3;
ListNode node=AddTwoNumbersLc.addTwoNumbers(l1_1, l2_1);
while(node!=null){
System.out.println(node.val);
node=node.next;
}
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head=null;
ListNode currentNode=null;
ListNode l1current=l1;
ListNode l2current=l2;
int isPlus=0;
while(l1current!=null||l2current!=null){
if(l1current==null)
l1current=new ListNode(0);
if(l2current==null)
l2current=new ListNode(0);
int sumVal=l1current.val+l2current.val+isPlus;
int nodeVal=sumVal%10;
isPlus=sumVal/10;
if(head==null){
head=new ListNode(nodeVal);
currentNode=head;
}else{
currentNode.next=new ListNode(nodeVal);
currentNode=currentNode.next;
}
l1current=l1current.next;
l2current=l2current.next;
}
if(isPlus!=0){
currentNode.next=new ListNode(isPlus);
}
return head;
}
static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
}
解法二:
package com.lipeng.leetcode;
/**
* 实现思路:
* 这是LeetCode网上的一种最优解法,思路和我上面写的一样,但写法更加优雅。
* 相比之下,我还是水平太LOW。
* @author Others
* @date 2018年1月24日
*/
public class AddTwoNumbersLc {
public static void main(String[] args) {
ListNode l1_1=new ListNode(2);
ListNode l1_2=new ListNode(4);
ListNode l1_3=new ListNode(3);
l1_1.next=l1_2;
l1_2.next=l1_3;
ListNode l2_1=new ListNode(5);
ListNode l2_2=new ListNode(6);
ListNode l2_3=new ListNode(4);
l2_1.next=l2_2;
l2_2.next=l2_3;
ListNode node=AddTwoNumbersLc.addTwoNumbers(l1_1, l2_1);
while(node!=null){
System.out.println(node.val);
node=node.next;
}
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
}