2. Add Two Numbers

来源:互联网 发布:java 手写数字识别 编辑:程序博客网 时间:2024/06/05 19:41

问题: 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

问题描述:用链表首节点表示个位,下一个结点表示十位一次类推,实现相加。

解题思路:本道题注重链表的使用。首先用一个变量表示进位,将同一位的数字相加并且加上进位取余,才是和值当前位的数值。当两个链表长度不同的时候,将已经为空的结点值赋为0,再进行相加取余。当两个结点都为空的时候,若进位为1,将和值的下一个结点(也就是最后一个结点)的值设为1。

注意事项: 1.当前结点为空时不能访问下一个结点,否则会抛出异常。
2.开始需要先初始化一个结点,并且设定一个链表结点指向它。对其的下一个结点进行计算,返回的时候才能得到所要的值。

/** * 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) {                    int sign = 0;                             ListNode l3 = new ListNode(0);//初始化和值结点,不能初始化为null,否则无法访问下一个结点。                    ListNode dummy = l3;//起到一个定位的作用,返回的时候可以得到个位。                    int judge;                    while(l1 != null || l2 != null){//只有其中的一个非空,就可以继续进行计算。                        int x = (l1 == null) ? 0 : l1.val;                        int y = (l2 == null) ? 0 : l2.val;                        judge = x + y + sign;                        l3.next = new ListNode( judge % 10 );                        // if(judge < 10) sign = 0;                        // else sign = 1;                        sign = judge/10;                        l3 = l3.next;                        if(l1 != null)l1 = l1.next;                        if(l2 != null)l2 = l2.next;                    }                    if(sign == 1) {                        l3.next = new ListNode(sign);                    }                    return  dummy.next;                  }}
原创粉丝点击