zoukankan      html  css  js  c++  java
  • 2.Add Two Numbers

    题目

    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


    解题思路

    1. 主要的单链表操作,注意最后的进位。时间复杂度O(max|m,n|)。空间复杂度O(max|m,n|)。(√)


    代码

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
         
            ListNode head=null,tail=null;
            int first=1;
            int sum;
            int flag=0;
    
            while(l1!=null || l2!=null){
                sum=flag;
                if(l1!=null && l2!=null){sum+=l1.val+l2.val;l1=l1.next;l2=l2.next;}
                else if(l1!=null){sum+=l1.val;l1=l1.next;}
                else {sum+=l2.val;l2=l2.next;}
    
                flag=sum/10;
    
                ListNode node = new ListNode(sum%10);
    
                if(first==1){
                    first=0;
                    head=node;
                    tail=node;
                }else{   
                    tail.next=node;
                    tail=node;
                }   
                
            }
            
            if(flag!=0){
                ListNode node = new ListNode(flag);
                tail.next=node;
            }
    
            return head;
        }
        
    }


    执行结果




  • 相关阅读:
    jquery扩展
    [转][C#]加密解密类
    [转][C#]压缩解压
    [转][C#]程序的动态编译
    [转][C#]Linq 的扩展方法
    [转]Oracle left join right join
    [转]检测到有潜在危险的 Request.Form 值
    IIS 添加 MIME
    [转][Echarts]俄罗斯方块
    01-python爬虫之常见的加密方式
  • 原文地址:https://www.cnblogs.com/gccbuaa/p/6819413.html
Copyright © 2011-2022 走看看