002

来源:互联网 发布:淘宝多寄了东西怎么办 编辑:程序博客网 时间:2024/04/16 13:07

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8


输入:两个都是list,输出也是list

不会有括号


思路,简单的nodes

list


可以操作符重载,不过没有必要

要求是写函数

-------------------------------------------

在指针的地方卡住了

为什么会漂浮呢?

很多c++的东西忘记了

-------------------------------------------

好累啊

大脑怎么转不过来呢?

-----------------------------




class Solution {
public:
//ListNode *out;


    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        //ListNode *out;
        ListNode *h1,*h2,*ho;
        ListNode *out=new ListNode(0);
  ho=out;
        //ListNode *out=new ListNode(0);
        int tp;
        //cout<<l1->val<<" "<<l2->next->val<<endl;
        bool f=false;


        int val1=0,val2=0;
        for(h1=l1,h2=l2;h1!=NULL || h2!=NULL;){
       
        if(f)
        tp=1;
        else
        tp=0;
val1=0;
        val2=0;
        if(h1!=NULL){
        val1=h1->val;
        }
        if(h2!=NULL)
        val2=h2->val;
      


        tp=val1+val2+tp;


        if(tp>9)
        f=true;
        else
        f=false;


        tp=tp%10;
        //cout<<tp<<endl;
        out->next=new ListNode(tp);
       
        out=out->next;
        //cout<<ho->next->val;
        if(h1)
        h1=h1->next;
        if(h2)
        h2=h2->next;
        }
        if(f){
        tp=1;
        out->next=new ListNode(tp);
       out=out->next;
}
        //cout<<ho->next->val<<endl;
return ho->next;
    }
};
-----------------------
好捷豹菜啊
能不能
想清楚再写啊

0 0
原创粉丝点击