add two number
题目要求:
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
public class ListNode {
int val;
ListNode next=null;
ListNode(int x) {
val = x;
next = null;
}
}
.
public class Solution {
public static void main(String[] args) {
ListNode listNodeL1=new ListNode(1);
ListNode listNodeL1_2=new ListNode(2);
ListNode listNodeL1_3=new ListNode(3);
listNodeL1.next=listNodeL1_2;
listNodeL1_2.next=listNodeL1_3;
listNodeL1_3.next=null;
ListNode listNodeL2=new ListNode(1);
ListNode listNodeL2_2=new ListNode(2);
ListNode listNodeL2_3=new ListNode(3);
listNodeL2.next=listNodeL2_2;
listNodeL2_2.next=listNodeL2_3;
listNodeL2_3.next=null;
Solution solution = new Solution();
ListNode rs= solution.addTwoNumbers(listNodeL1,listNodeL2);
while (rs!=null){
System.out.println(rs.val);
rs=rs.next;
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode rs=new ListNode(0);
ListNode cur=rs;
int carry = 0;
int i = 0;
int j = 0;
while (l1 != null || l2 != null) {
if (l1 != null) {
i = l1.val;
l1=l1.next;
}
if (l2 != null) {
j = l2.val;
l2 = l2.next;
}
int sum = i + j + carry; //如果大于10 进位
cur.next=new ListNode(sum%10); //创建一个新的节点
cur=cur.next; //把下个节点和当前节点连起来
carry=sum/10;//算进位
}
if(carry>0) cur.next=new ListNode(carry);
return rs.next;
}
}