题目
题解
题解一:
这题其实比较简单,无非就是注意一下进位。
大概思路就是长链表一直要循环遍历完,从长链表头与短链表头依次相加,然后短的先于长的遍历完后,
若有进位,则长的剩下一段与进位相加
若长链表遍历完后,仍然有进位 则需要增加一位 尾位置为1
然后按照这个思路 自己写了一个解法,但是不够优美
代码
自己的解法
package No_2;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;
public class Solution {
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode();
ListNode tempNode = head;
int flag = 0;
while (l1 != null && l2 != null){
int temp = l1.val + l2.val + flag;
if (temp > 9){
tempNode.next = new ListNode(temp-10);
flag = 1;
}else {
tempNode.next = new ListNode(temp);
flag = 0;
}
l1 = l1.next;
l2 = l2.next;
tempNode = tempNode.next;
}
if (l2 != null)
l1 = l2;
while (l1 != null){
int temp = l1.val + flag;
if (temp > 9){
tempNode.next = new ListNode(temp-10);
flag = 1;
}else {
tempNode.next = new ListNode(temp);
flag = 0;
}
l1 = l1.next;
tempNode = tempNode.next;
}
if (flag!=0)
tempNode.next = new ListNode(1);
return head.next;
}
}
官方解法
public class Solution_1 {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null;
ListNode tail = null;
int flag = 0;
while (l1 != null || l2 != null){
int n1 = l1 != null ? l1.val : 0;
int n2 = l2 != null ? l2.val : 0;
int sum = n1 + n2 + flag;
if (head == null){
head = tail = new ListNode(sum % 10);
}else {
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
flag = sum/10;
if (l1 != null){
l1 = l1.next;
}
if (l2 != null){
l2 = l2.next;
}
}
if (flag != 0)
tail.next = new ListNode(flag);
return head;
}
}