Add Two Numbers
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.
思路
從頭節(jié)點開始遍歷這兩個鏈表,將每一個對應節(jié)點進行相加,結果再除以
10
作為下一位相加的進位磷籍,同時記錄余數
作為本位的結果们镜,一直處理蝙泼,直到所有的結點都處理完;當兩個鏈表都到末尾時探孝,判斷當前進位是否為
1
辩涝,是的話則增加新節(jié)點霍狰,值為1
;否則直接返回結果;當其中一個鏈表未到末尾時砚哗,將新鏈表尾部
next
指向此鏈表的next
位置婚陪,并判斷進位是否為1
,為1
的話則執(zhí)行類似第一步的操作频祝,直到進行為0
泌参,返回結果.-
實現代碼:
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public ListNode addTwoNumbers(ListNode head1, ListNode head2) { if(null == head1 || null == head2) { return null; } ListNode head = new ListNode(0); // 建立新鏈表的頭節(jié)點 ListNode result = head; int carry = 0; // 進位,值為 1 或 0 while (head1.next != null && head2.next != null) { head1 = head1.next; head2 = head2.next; int val = (head1.val + head2.val + carry) % 10; carry = (head1.val + head2.val + carry) / 10; head.next = new ListNode(val); head = head.next; } if (head1.next != null) { // 鏈表1未結束 head.next = head1.next; } else if (head2.next != null) { // 鏈表2未結束 head.next = head2.next; } if (carry == 1) { // 有進位則繼續(xù)遍歷鏈表 while (head.next != null) { head = head.next; int temp = head.val + carry; head.val = temp % 10; carry = temp / 10; } if (carry == 1) { head.next = new ListNode(1); } } return result; }