leetcode add two numbers

来源:互联网 发布:事件驱动模型 php 编辑:程序博客网 时间:2024/05/16 11:30

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

意思是用链表实现两个数相加。


思路:求余,作为当前节点的val,求商作为进位数。另外还要注意两个链表长度不一的情况。话不多数,看代码

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        //判断非空        if(l1==null)        {            return l2;        }        if(l2==null)        {            return l1;        }                ListNode     p=l1,//用来操作l1                     q=l2;//用来操作l2        ListNode New = new ListNode(0);//创建一个新的节点        ListNode    r = New;//用来实现链表的链接                New.next = p;                        int sum;        int another=0;                while(p!=null&&q!=null)        {            sum   = p.val + q.val + another;            p.val = sum%10;            another = sum/10;            r     = p;            p     = p.next;            q     = q.next;        }                if(p==null)        {            r.next=q;//l1短,和l2多余部分接起来        }else{            r.next = p;//l1长,就直接用下去        }        //l1 or l2 走完以后,还有进位        if(another==1)        {            while(r.next!=null)//有一支链表还没有走完            {                sum = r.next.val + another;//有一支链表走完了,所以只加一个数                r.next.val = sum%10;                another = sum/10;                r = r.next;            }                        if(another==1)            {                r.next = new ListNode(another);            }        }        return New.next;            }}

原创粉丝点击