zoukankan      html  css  js  c++  java
  • 002两数相加

    写在前面,参考的力扣官网的画解算法

    链表

    /*
     * @lc app=leetcode.cn id=2 lang=java
     *
     * [2] 两数相加
     */
    
    // @lc code=start
    /**
     * 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) {
    
            //Tips:对于链表问题,返回结果为头结点时,通常需要先初始化一个预先指针pre
            //该指针的下一个节点指向真正的头结点head
            //使用预先指针的目的在于链表初始化时无可用节点值,而且链表的构造过程需要指针移动
            //而且会导致头指针丢失,无法返回结果
    
            //添加预指针pre
            ListNode pre=new ListNode(0);
            //cur也指向pre
            ListNode cur=pre;
            //进位为0
            int carry=0;
    
            //将两个链表看成是相同长度的进行遍历
            while(l1!=null || l2!=null){
    
                //如果一个链表较短则在前面补0
                int x=l1==null?0:l1.val;
                int y=l2==null?0:l2.val;
    
                //每一位计算的同时需要考虑上一位的进位问题
                int sum=x+y+carry;
    
                //而当前位计算结束后同样需要更新进位值
               
                //进位值变化
                carry=sum/10;
                //实际存入链表
                sum=sum%10;
                cur.next=new ListNode(sum);
    
                //添加节点并移动l1,l2.cur
                cur=cur.next;
                if(l1!=null)
                    l1=l1.next;
                if(l2!=null)
                    l2=l2.next;
            }
    
             //如果两个链表全部遍历完毕后,进位值为1,则在新链表最前方添加节点1
            if(carry==1){
                cur.next=new ListNode(carry);
            }
            //从pre.next开始返回改链表
            return pre.next;
        }
    }
    // @lc code=end
    
    
    
  • 相关阅读:
    数学工具WZgrapher
    零线和地线的区别,示波器如何测量市电?
    使用直流稳压电源时的注意事项!
    中文全角和半角输入有什么区别?
    ThinkingRock:使用方法
    2014记首
    如何使用Excel绘制甘特图
    AStyle代码格式工具在source insight中的使用
    STM32F103系列命名规则
    上市公司行情查询站点
  • 原文地址:https://www.cnblogs.com/lxr-xiaorong/p/13438558.html
Copyright © 2011-2022 走看看