两数相加 Posted on 2020-09-08 | In leetcode | 本文总阅读量 次 leetcode: 两数相加对于链表长度头部未知的,可在头部前多设一个节点来快速获取 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode temList1,temList2,newList,newTemList; temList1 = l1; temList2 = l2; int carryBit = 0, newBit = 0; newList = new ListNode(0); newTemList = newList; while(true){ if(temList1 == null){ while(temList2 != null){ newBit = temList2.val + carryBit; if(newBit > 9){ carryBit = 1; newBit = newBit - 10; }else{ carryBit = 0; } newTemList.next = new ListNode(newBit); newTemList = newTemList.next; temList2 = temList2.next; } break; } if(temList2 == null){ while(temList1 != null){ newBit = temList1.val + carryBit; if(newBit > 9){ carryBit = 1; newBit = newBit - 10; }else{ carryBit = 0; } newTemList.next = new ListNode(newBit); newTemList = newTemList.next; temList1 = temList1.next; } break; } newBit = temList1.val + temList2.val + carryBit; if(newBit > 9){ carryBit = 1; newBit = newBit - 10; } else{ carryBit = 0; } newTemList.next = new ListNode(newBit); newTemList = newTemList.next; temList1 = temList1.next; temList2 = temList2.next; } if(carryBit == 1){ newTemList.next = new ListNode(1); } return newList.next; } }