问题:
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