問題:
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
描述:
輸入(2 -> 4 -> 3) + (5 -> 6 -> 4)即:342 + 465兩個整數的加法運算。
注意:1,加法運算過程中的進位。
2,兩個數位數不相等的時候。 (9 --> 9) + 1
3,最高位有進位的時候位數需要增加一位。 (9 --> 9) + 1 = (0 --> 0 --> 1)
public class AddTwoNumbers {
public static ListNode addTwoNumbers(ListNode l1, ListNode l2){
ListNode start = new ListNode(0);
ListNode index = start;
int carry=0;
int temp=0;
while(null !=l1 || null !=l2){
int x= (l1!= null) ?l1.val : 0;
int y= (l2!= null) ?l2.val : 0;
temp=x+y+carry;
carry = temp/10;
index.next = new ListNode(temp%10);
index = index.next;
if(l1!=null) l1=l1.next;
if(l2!=null) l2=l2.next;
}
if(carry==1)
index.next=new ListNode(carry);
return start.next;
}
}
class ListNode {
int val;
ListNode next;
public ListNode(int x) {
val = x;
}
}
總結:鏈表的增加問題
* 1,要將7-->8-->0加入到鏈表中,首先應建立首鏈表
* listNode start = new listNode(0);
* listNode index = start;//將index作爲指針,指向start節點
* 2,然後再用index指針操作鏈表的增加
* index.next = new listNode(7);
* index = index.next;
* 3,依次添加節點到鏈表
* index.next = new listNode(8);
* index = index.next;
(2 -> 4 -> 3)
*
(5 -> 6 -> 4)
---------------------
0 --> 1 --> 7 -->1
十位加一個0 0 --> 2 --> 5 -->0 -->2
百位加倆個0 0 --> 0 --> 8 -->6 -->3 -->1
-----------------------------------
+
-----------------------------------
0 --> 3 --> 0 -->9 -->5 -->1