public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode rs = new ListNode(l1.val + l2.val);
l1 = l1.next;
l2 = l2.next;
ListNode temp = rs;
//先假设ab都等于0,即两个链表都为空,
while (l1 != null || l2 != null) {
int a = 0;
int b = 0;
if (l1 != null) {
a = l1.val;
}
if (l2 != null) {
b = l2.val;
}
//两者相加并存储,同时判断条件三个链表各自后移
int t = a + b;
temp.next = new ListNode(t);
temp = temp.next;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
temp = rs;
//判断temp上的数值是否大于10,大于10则减去10,下一位加1,下一位为空则新建0节点再加一
while (temp != null) {
if (temp.val >= 10) {
temp.val = temp.val - 10;
if (temp.next == null) {
temp.next = new ListNode(0);
}
temp.next.val = temp.next.val + 1;
}
temp = temp.next;
}
return rs;
}
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre = new ListNode(0);
pre.next = head;
ListNode start = pre, end = pre;
while(n != 0) {
start = start.next;
n--;
}
while(start.next != null) {
start = start.next;
end = end.next;
}
end.next = end.next.next;
return pre.next;
}
原文:https://www.cnblogs.com/dong-qing/p/14626121.html