2. 两数相加
这道题唯一的难点就是cur如何往后移
题目:


题解:
java
/**
* Definition for singly-linked list.
* public 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 list = new ListNode(0);
ListNode cur = list;
int y = 0;
while(l1 != null && l2 != null) {
cur.next = new ListNode((l1.val + l2.val + y) % 10);
y = (l1.val + l2.val + y) / 10;
l1 = l1.next;
l2 = l2.next;
cur = cur.next;
}
while(l1 != null) {
cur.next = new ListNode((l1.val + y) % 10);
y = (l1.val + y) / 10;
l1 = l1.next;
cur = cur.next;
}
while(l2 != null) {
cur.next = new ListNode((l2.val + y) % 10);
y = (l2.val + y) / 10;
l2 = l2.next;
cur = cur.next;
}
if(y != 0) {
cur.next = new ListNode(y);
cur = cur.next;
}
//当前头是虚拟头,所以真正的链表是next之后的
return list.next;
}
}