链表求和

来源:互联网 发布:淘宝有卖寿衣 编辑:程序博客网 时间:2024/05/19 20:20

 链表求和

 

 

你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。

样例

给出两个链表 3->1->5->null  5->9->2->null,返回8->0->8->null

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null;       *     } * } */public class Solution {    /**     * @param l1: the first list     * @param l2: the second list     * @return: the sum list of l1 and l2      */    public ListNode addLists(ListNode l1, ListNode l2) {        // write your code here        ListNode root=null,cur=null;        int flag = 0;        while(l1 !=null && l2!=null){            int val = l1.val + l2.val +flag;            flag = val / 10;            val = val % 10;                        ListNode temp = new ListNode(val);            if(root == null){                root = temp;            }            if(cur != null){                cur.next = temp;            }            cur = temp;            l1 = l1.next;            l2 = l2.next;                    }        while(l1 != null){            int val = l1.val + flag;            flag = val / 10;            val %= 10;            ListNode temp = new ListNode(val);            if(root == null){                root = temp;            }            if(cur != null){                cur.next = temp;            }            cur = temp;            l1 = l1.next;        }        while(l2 != null){            int val = l2.val + flag;            flag = val / 10;            val %= 10;            ListNode temp = new ListNode(val);            if(root == null){                root = temp;            }            if(cur != null){                cur.next = temp;            }            cur = temp;            l2 = l2.next;        }        if(flag == 1){            ListNode temp = new ListNode(flag);            cur.next = temp;        }        return root;    }}

0 0
原创粉丝点击