链式A+B

来源:互联网 发布:java和net就业前景 编辑:程序博客网 时间:2024/06/05 04:05

题目描述

有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。

给定两个链表ListNode* A,ListNode* B,请返回A+B的结果(ListNode*)。

测试样例:

{1,2,3},{3,2,1}

返回:{4,4,4}

import java.util.*;/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/public class Plus {    public ListNode plusAB(ListNode a, ListNode b) {        // write code here        if(a==null) return b;        if(b==null) return a;        ListNode res = null, r = null;        int carry = 0;        boolean flag = false;        while(a!=null&&b!=null){            int p = a.val + b.val + carry;            if(flag==false){                res = new ListNode(p%10);                r = res;                carry = p/10;                flag = true;            }else{                res.next = new ListNode(p%10);                carry = p/10;                res = res.next;            }            a = a.next;            b = b.next;        }                while(a!=null){            res.next = new ListNode((a.val+carry)%10);            carry = (a.val+carry)/10;            res = res.next;            a = a.next;        }                while(b!=null){            res.next = new ListNode((b.val+carry)%10);            carry = (b.val+carry)/10;            res = res.next;            b = b.next;        }                if(carry!=0){            res.next = new ListNode(carry); //注意最高位的相加也可能产生进位动作        }        return r;    }}




0 0