LeetCode 2. 两数相加
2. 两数相加
Solution
思路:模拟。自己的写法是两个一起循环,其中一个结束就停止循环,再处理另一个链表,不过也可以一直循环,但是可以直接连接过去,然后就是考虑进位。
//class ListNode {
// int val;
// ListNode next;
// ListNode() {}
// ListNode(int val) { this.val = val; }
// ListNode(int val, ListNode next) { this.val = val; this.next = next; }
//}
//写法有点点丑
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode root = new ListNode();
int preDigit = 0;
ListNode p = root;
while (l1 != null && l2 != null) {
ListNode t = new ListNode();
int x = l1.val, y = l2.val;
t.val = (x + y + preDigit) % 10;
preDigit = (x + y + preDigit) / 10;
p.next = t;
p = t;
l1 = l1.next;
l2 = l2.next;
}
if (l2 != null) {
l1 = l2;
}
while (l1 != null) {
ListNode t = new ListNode();
t.val = (l1.val + preDigit) % 10;
preDigit = (l1.val + preDigit) / 10;
if (preDigit == 0) {
t.next = l1.next;
p.next = t;
break;
}
p.next = t;
p = t;
l1 = l1.next;
}
if (preDigit != 0) {
ListNode t = new ListNode();
t.val = preDigit;
p.next = t;
t.next = null;
}
return root.next;
}
}
// 优雅 但是内存多一点点
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null, tail = null;
int digit = 0;
while (l1 != null || l2 != null) {
int val1 = l1 != null ? l1.val : 0;
int val2 = l2 != null ? l2.val : 0;
int sum = val1 + val2 + digit;
if (head == null) {
head = new ListNode(sum % 10);
tail = head;
} else {
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
digit = sum / 10;
if (l1 != null)
l1 = l1.next;
if (l2 != null)
l2 = l2.next;
}
if (digit != 0) {
tail.next = new ListNode(digit);
}
return head;
}
}
埋骨何须桑梓地,人生无处不青山