class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public Solution() {}
// TODO Auto-generated constructor stub
static public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//伪代码:
//设置一个哑节点re_head保持结果链表。
//curr1,curr2初始化为l1,l2的头结点
//初始化carry为0
//使用curr1,curr2遍历两个链表l1,l2
//sum=curr1+curr2+carry。curr1或curr2为空节点则在本公式运算中取值为0。
//根据sum的个位上的数建立结果链表当前节点。根据sum的十位上的数决定是否有进位,有进位carry为1。
//遍历结束,carry为1,在结果链表末尾再增加一节点。
//
ListNode head1=l1;
ListNode head2=l2;
ListNode re_head = new ListNode(0);
ListNode re_curr = re_head;
ListNode curr1 = head1;
ListNode curr2 = head2;
int carry =0;//进位
while(curr1 !=null|| curr2!=null){
//System.out.println("curr1.val"+curr1.val);
//System.out.println("curr2.val"+curr2.val);
int sum=0;
if(curr1 !=null){
sum += curr1.val;
}
if(curr2 !=null){
sum += curr2.val;
}
sum += carry;
if(sum>9)
{
carry =1;
re_curr.next = new ListNode(sum-10);
} else{
carry = 0;
re_curr.next = new ListNode(sum);
}
//陷阱:在while的条件下,curr1或curr2可能为null
if(curr1 != null){
curr1= curr1.next;
}
if(curr2 != null){
curr2 = curr2.next;
}
re_curr = re_curr.next;
}
if(carry ==1){
re_curr.next = new ListNode(1);
}
//输出re链表
re_curr = re_head.next;
do{
System.out.print(re_curr.val);
re_curr = re_curr.next;
if(re_curr != null){
System.out.print(" -> ");
}
}while(re_curr != null);
return re_head.next;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode l1=new ListNode(8);
l1.next=new ListNode(1);
ListNode l2=new ListNode(0);
Solution.addTwoNumbers(l1, l2);
}
}