Leetcode || Add Two Numbers

来源:互联网 发布:k近邻算法流程图 编辑:程序博客网 时间:2024/05/02 02:55

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

class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        ListNode p1 = l1;        ListNode p2 = l2;        ListNode head = new ListNode(0);        ListNode p3 = head;        int add_value=0;        int a = 0;        while(p1!=null || p2!=null) { //链表向后遍历,直到两者都为空            if(p1!=null) {                add_value += p1.val;                p1 = p1.next;            }            if(p2!=null) {                add_value += p2.val;                p2 = p2.next;            }            p3.next = new ListNode(add_value%10);            p3 = p3.next;            a = add_value; //保存和            if(add_value > 9)                add_value = 1;            else                 add_value = 0;        }        if(a > 9) { //最高位有进位            p3.next = new ListNode(1);        }        return head.next;    }}
0 0
原创粉丝点击