• 【Leecode】两数相加


    学习了链表结构,链表中元素的访问,对象指针的初始化与赋值,链表的创建(多个节点链接起来),进位计算的表达。

    100ms

    /**
     * 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* sum = new ListNode(0);
            ListNode* tmp = sum;
            int carry = 0; 
            
            while(l1 || l2) 
            {
                if(l1)
                {
                    carry += l1->val;
                    l1 = l1->next;
                }
                if(l2)
                {
                    carry += l2->val;
                    l2 = l2->next;
                }
                
                tmp->next = new ListNode(carry % 10);
                carry /= 10;
                tmp = tmp->next;
            }
            
            if(carry)
                tmp->next = new ListNode(carry);
            
            return sum->next;
        }
    };

    68ms

    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode *L = new ListNode(0), *p = L;
            int m = 0; //进位值
            int x, y; //保存l1 l2节点的值
                  
            while(l1 || l2){ //题目中的链表是没有header的
                x = (l1 != NULL) ? l1->val : 0;
                y = (l2 != NULL) ? l2->val : 0;
                p->val = (x + y + m) % 10;
    
                m = (x + y + m) > 9;
                cout << x << y << m << endl;
                
                l1 = (l1 != NULL) ? l1->next : NULL;
                l2 = (l2 != NULL) ? l2->next : NULL;
    
                p->next = ((l1 || l2) || m != 0) ? new ListNode(m) : NULL; // 如果仅判断(l1 || l2)的话,5+5 的情况会丢失进位
                p ? p = p->next : 0;
            }
            return L;
        }
    };
  • 相关阅读:
    4. Median of Two Sorted Arrays
    680. Valid Palindrome II
    11. Container With Most Water
    10. Regular Expression Matching
    1_Utilities__deviceQuery + 1_Utilities__deviceQueryDrv + 1_Utilities__topologyQuery
    1_Utilities__bandwidthTest
    CUDA C Programming Guide 在线教程学习笔记 Part 11
    hdu 3790 最短路径问题
    hdu 1050 Moving Tables
    斯特林公式 hdu1018
  • 原文地址:https://www.cnblogs.com/gdut-gordon/p/10513156.html
Copyright © 2020-2023  润新知