zoukankan      html  css  js  c++  java
  • 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

    思路:

    从头到后的顺序,注意有进位,一个小技巧就是先是在程序判断两边都还有数字,均不为空,再判断谁已经“ 出局 ”。

    代码:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode *dummy=new ListNode(0);
            ListNode *tail=dummy;
            int flag=0;
            
            while(l1||l2){
                int m=0;
                if(l1){
                    m+=l1->val;
                    l1=l1->next;
                }
                
                if(l2){
                    m+=l2->val;
                    l2=l2->next;
                }
                m=m+flag;
                
                ListNode *tmp=new ListNode(m%10);
                flag=m/10;
                tail->next=tmp;
                tail=tail->next;
            }
            
            if(flag){
                ListNode *tmp=new ListNode(flag);
                tail->next=tmp;
            }
            return dummy->next;
        }
    };


  • 相关阅读:
    [剑指 Offer 11. 旋转数组的最小数字]
    进程描述符(PCB)
    [剑指 Offer 57. 和为s的两个数字]
    Linux netstat命令
    kafka2.3.X配置文件
    docker
    shell操作mysql数据库
    Linux文件查找之find命令
    sed 切割日志文件
    Linux文本处理之awk
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519826.html
Copyright © 2011-2022 走看看