難度 中等
最近做題的速度提上來(lái)了含蓉,或許是因?yàn)橹R(shí)點(diǎn)一點(diǎn)點(diǎn)拾回來(lái)了频敛,不過(guò)總這樣也不算好事,說(shuō)明沒(méi)有新的知識(shí)點(diǎn)出現(xiàn)馅扣。這道題需要把鏈表反轉(zhuǎn)相加斟赚,我這里是直接反轉(zhuǎn)了,用棧也可以差油,速度會(huì)更快一些拗军,不過(guò)要犧牲一些空間。需要注意的還有一些細(xì)節(jié)蓄喇,兩數(shù)相加進(jìn)位可能會(huì)連續(xù)進(jìn)位发侵,連續(xù)進(jìn)位過(guò)程中l(wèi)1或l2可能會(huì)被遍歷完而為空,需要考慮到這一點(diǎn)妆偏。
執(zhí)行用時(shí) :3 ms, 在所有 Java 提交中擊敗了83.33%的用戶
內(nèi)存消耗 :39.7 MB, 在所有 Java 提交中擊敗了95.83%的用戶
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
l1 = reverseList(l1);
l2 = reverseList(l2);
ListNode l3 = null;
ListNode cur = null;
int r = 0;
while(l1 != null && l2 != null || r == 1){
int sum = 0;
if(l1 != null && l2 != null){
sum = l1.val + l2.val + r;
l1 = l1.next;
l2 = l2.next;
}else if(r == 1 && l1 != null){
sum = l1.val + r;
l1 = l1.next;
}else if(r == 1 && l2 != null){
sum = l2.val + r;
l2 = l2.next;
}else if(r == 1){
sum = r;
}
r = sum/10;
ListNode temp = new ListNode(sum%10);
if(cur == null){
l3 = temp;
cur = temp;
}else{
cur.next = temp;
cur = cur.next;
}
}
if(l1 != null){
cur.next = l1;
}else if(l2 != null){
cur.next = l2;
}else{
cur.next = null;
}
l3 = reverseList(l3);
return l3;
}
public ListNode reverseList(ListNode l){
ListNode cur = l;
ListNode nTail = null;
while(cur != null){
ListNode nHead = new ListNode(cur.val);
nHead.next = nTail;
nTail = nHead;
cur = cur.next;
}
l = nTail;
return nTail;
}