C++ 链式A+B

#include<iostream>
using namespace std;

/**
有两个用链表表示的整数,每个结点包含一个数位。
这些数位是反向存放的,也就是个位排在链表的首部。
编写函数对这两个整数求和,并用链表形式返回结果。
给定两个链表ListNode* A,ListNode* B,请返回A+B的结果(ListNode*)

算法:
使用两个指针分别指向链表A和链表B的首部,并分别将对应的当前元素相加

**/

struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Plus {
public:
    ListNode* plusAB(ListNode* a, ListNode* b) {
        // write code here

        //cout<<"enter the function"<<endl;

        if(a==NULL){
            return b;
        }
        if(b==NULL){
            return a;
        }
        ListNode *out_head=new ListNode(0);
        ListNode *out=out_head;
        bool flag=false;
        while(a!=NULL and b!=NULL){
            int temp=a->val+b->val;
            if(flag==true){
                temp++;
            }
            if(temp>=10){
                flag=true;
                temp=temp%10;
            }
            else{
                flag=false;
            }

            //cout<<temp<<"temp"<<endl;

            ListNode *new_node=new ListNode(temp);
            out->next=new_node;
            out=out->next;

            a=a->next;
            b=b->next;

        }

        //cout<<"outside while loop"<<endl;

        ListNode *extend;
        if(a!=NULL){
            extend=a;
        }
        if(b!=NULL){
            //cout<<"extend"<<endl;
            extend=b;
        }
        if(flag==false){
            out->next=extend;
        }
        else{
            // flag=true,need to be 进位
            while(extend!=NULL){
                int temp=extend->val+1;
                if(temp>=10){
                    flag=true;
                    temp=temp%10;
                }
                else{
                    flag=false;
                }
                ListNode *new_node=new ListNode(temp);
                out->next=new_node;
                out=out->next;

                extend=extend->next;
            }
            if(flag==true){
                ListNode *new_node=new ListNode(1);
                out->next=new_node;
            }
        }
        return out_head->next;
    }
};

int main(){
    int array_a[3]={1,2,3};
    ListNode *head_a=new ListNode(0);
    ListNode *a=head_a;

    int array_b[7]={3,2,9,9,9,9,2};
    ListNode *head_b=new ListNode(0);
    ListNode *b=head_b;

    for(int i=0;i<3;i++){
        ListNode *new_node=new ListNode(array_a[i]);
        a->next=new_node;
        a=a->next;
    }

    for(int j=0;j<7;j++){
        ListNode *new_node=new ListNode(array_b[j]);
        b->next=new_node;
        b=b->next;
    }
    Plus solution;
    ListNode *out;
    out=solution.plusAB(head_a->next,head_b->next);

    while(out!=NULL){
        cout<<"output"<<out->val<<endl;
        out=out->next;
    }

    return 0;
}

 

<think>我们正在讨论C++中的链式调用(也称为方法链)的实现原理和示例。链式调用是一种编程风格,允许在单个对象上连续调用多个方法,每个方法返回对象本身(或同类型的另一个对象)的引用,从而可以连续调用。 ### 原理 链式调用的核心在于:每个方法在完成操作后返回对象自身的引用(通常是`*this`)。这样,返回的引用可以立即用于调用下一个方法。这种方式常见于构建器模式(Builder Pattern)或流式接口(Fluent Interface)。 ### 示例 下面是一个简单的示例,展示如何实现一个支持链式调用的`StringBuilder`类: ```cpp #include <iostream> #include <string> class StringBuilder { private: std::string data; public: StringBuilder& append(const std::string& str) { data += str; return *this; // 返回当前对象的引用 } StringBuilder& appendLine(const std::string& str) { data += str + "\n"; return *this; } std::string toString() const { return data; } }; int main() { StringBuilder sb; sb.append("Hello, ").append("World!").appendLine(" This is a new line."); std::cout << sb.toString(); return 0; } ``` 在这个例子中: - `append`和`appendLine`方法都返回`StringBuilder&`(即当前对象的引用)。 - 因此,我们可以连续调用这些方法:`sb.append(...).append(...).appendLine(...)`。 ### 注意事项 1. **返回类型**:链式方法通常返回非const的引用(`return *this;`),这样可以在链式调用中修改对象状态。但有时如果是为了创建新对象,也可以返回一个新对象(例如,在不可变对象中)。 2. **常量方法**:如果某个方法不应该改变对象状态,那么应该将其声明为`const`,但这样的方法通常不能用于链式调用(除非返回一个新对象)。 3. **链式调用与临时对象**:链式调用可以用于临时对象,例如: ```cpp std::string result = StringBuilder().append("Hello").append("!").toString(); ``` ### 进阶:返回不同对象 有时,链式调用中的不同方法可能返回不同类型的对象(但通常这些类型有共同的基类或接口)。例如,在构建器模式中,不同的构建步骤可能返回不同的构建器类型,但最终都会返回一个可以构建最终对象的类型。 ### 示例:构建器模式中的链式调用 ```cpp class Pizza { public: class Builder { private: int size; bool cheese = false; bool pepperoni = false; bool bacon = false; public: Builder(int size) : size(size) {} Builder& addCheese() { cheese = true; return *this; } Builder& addPepperoni() { pepperoni = true; return *this; } Builder& addBacon() { bacon = true; return *this; } Pizza build() { return Pizza(*this); } }; private: Pizza(const Builder& builder) : size(builder.size), cheese(builder.cheese), pepperoni(builder.pepperoni), bacon(builder.bacon) {} int size; bool cheese; bool pepperoni; bool bacon; }; int main() { Pizza pizza = Pizza::Builder(12).addCheese().addPepperoni().addBacon().build(); // 使用pizza... return 0; } ``` 在这个例子中,`Pizza::Builder`的每个添加配料的方法都返回构建器自身的引用,从而允许链式调用,最后调用`build()`方法生成`Pizza`对象。 ### 总结 C++中实现链式调用的关键在于让方法返回对象自身的引用(或另一个支持链式调用的对象的引用)。这种技术使得代码更加简洁和易读,特别适用于配置对象或构建复杂对象。 §§相关问题§§ 1. 链式调用在C++中会带来性能开销吗? 2. 链式调用与函数式编程中的组合有何异同? 3. 如何避免链式调用中的错误处理?</think>### C++ 方法链实现原理及示例 #### 一、实现原理 方法链(链式调用)的核心原理是:**每个方法执行后返回对象自身的引用**(通常是 `*this`)。通过返回当前对象的引用,使得后续方法可以继续在同一个对象上操作,形成连续的调用链。关键点包括: 1. **返回值类型**:方法返回当前类类型的引用(`ClassName&`) 2. **返回内容**:方法体末尾通过 `return *this;` 返回自身引用 3. **连续操作**:每个方法修改对象状态后返回自身,支持连续调用 #### 二、基础示例 ```cpp #include <iostream> #include <string> class Calculator { private: double value; public: Calculator() : value(0) {} // 链式方法:返回自身引用 Calculator& add(double x) { value += x; return *this; } Calculator& multiply(double x) { value *= x; return *this; } Calculator& print() { std::cout << "Result: " << value << std::endl; return *this; } }; int main() { Calculator calc; calc.add(5).multiply(3).add(10).print(); // 链式调用 // 输出:Result: 25 } ``` #### 三、进阶应用:构建器模式 方法链常用于构建复杂对象(Builder 模式): ```cpp class SQLQuery { private: std::string query; public: SQLQuery& select(const std::string& columns) { query = "SELECT " + columns; return *this; } SQLQuery& from(const std::string& table) { query += " FROM " + table; return *this; } SQLQuery& where(const std::string& condition) { query += " WHERE " + condition; return *this; } std::string build() const { return query + ";"; } }; // 使用示例 SQLQuery().select("name, age") .from("users") .where("age > 18") .build(); // 返回 "SELECT name, age FROM users WHERE age > 18;" ``` #### 四、技术细节 1. **返回值优化**: - 返回引用避免拷贝开销 - 支持临时对象链式调用:`Class().method1().method2()` 2. **常量方法**: ```cpp const Class& method() const { /* 只读操作 */ return *this; } ``` 3. **混合返回类型**: ```cpp class File { public: File& open() { /*...*/ return *this; } File& write() { /*...*/ return *this; } // 终结方法返回不同类型 std::string read() { return "data"; } }; ``` #### 五、应用场景 1. 流式接口设计(如`std::cout << a << b`) 2. 复杂对象构建(Builder 模式) 3. 函数式编程风格操作 4. 测试框架的断言链(如 `EXPECT(a).eq(b).lt(c)`) > **注意**:当方法需要返回新对象时(如数学运算),应返回值类型而非引用: > ```cpp > Vector3 operator+(const Vector3& other) const { > return Vector3(x+other.x, y+other.y, z+other.z); // 返回值类型 > } > ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值