Leetcode 用链表相加两个数
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
难度:medium
如题,每一个整数被反向储存在链表里,求两个数的和的链表
思路:先看共同部分:两个数相加,加上前一位的“进一”(如果有的话)mod 10,储存在新结点,新结点作为next结点,计算当前位的carry。之后再看单独部分。
挺简单的,直接看代码:
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null) return null;
int carry;
if (l1.val+l2.val > 9) carry = 1;
else carry = 0;
ListNode fake = new ListNode(0);
ListNode cur = new ListNode((l1.val+l2.val)%10);
fake.next = cur;
while (l1.next != null && l2.next != null){
l1 = l1.next;
l2 = l2.next;
cur.next = new ListNode((l1.val+l2.val+carry)%10);
cur = cur.next;
if (l1.val+l2.val+carry > 9) carry = 1;
else carry = 0;
}
while (l1.next != null){
l1 = l1.next;
cur.next = new ListNode((l1.val+carry)%10);
cur = cur.next;
if (l1.val+carry > 9) carry = 1;
else carry = 0;
}
while (l2.next != null){
l2 = l2.next;
cur.next = new ListNode((l2.val+carry)%10);
cur = cur.next;
if (l2.val+carry > 9) carry = 1;
else carry = 0;
}
if (carry == 1) cur.next = new ListNode(1);
return fake.next;
}
}
注意两点:第一位和最后一位比较特殊:第一位没有前一位的carry,而且因为需要return链表头,所以需要一个dummy head来储存链表头的结点(相加过程中当前结点一直在变);最后一位如果前一位有carry,最后一位+1
2ms,beat 95%,O(n), n=两个链表长度之和