[leetcode]2. Add Two Numbers.cpp

Posted on 2017-06-30 16:48  你猜我猜不猜你猜不猜  阅读(217)  评论(0)    收藏  举报
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

题目说给两个链表,其中是两个整数的逆序单数字串,求两个相加再逆序的链表。

例子说 (2->4->3)+(5->6->4) ==> 342+465=807 ==> 7->0->8

理解了题目就很好做了,类似大数相加的方法,一个一个加过去,设个cn保存一下进位,最后再处理一下cn,每次相加就直接创建一个新node放进去。

//
// Created by x on 2017/6/30.
//
#include<iostream>
#include<stack>
#include<vector>
using namespace std;
struct ListNode {
         int val;
         ListNode *next;
         ListNode(int x) : val(x), next(NULL) {}
};
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode* n1=l1;
    ListNode* n2=l2;
    vector<int> qe_re;
    int a,b,cn,re;
    a=b=cn=re=0;
    while(n1!=NULL || n2!=NULL){
        a=n1!=NULL?n1->val:0;
        b=n2!=NULL?n2->val:0;
        if(n1!=NULL) n1=n1->next;
        if(n2!=NULL) n2=n2->next;
        re=a+b+cn;
        cn=re/10;
        re=re%10;
        qe_re.push_back(re);
    }
    if(cn!=0)
        qe_re.push_back(cn);
    ListNode *result;
    if(qe_re.size()==0)
        return result;
    else{
        result = new ListNode(qe_re[0]);
    }
    ListNode *next = result;
    for(int i=1;i<qe_re.size();i++){
        next->next = new ListNode(qe_re[i]);
        next=next->next;
    }
    return result;
}

int main(){
    ListNode *p1=new ListNode(3);
    p1->next= new ListNode(2);
    ListNode *p2=new ListNode(5);
    ListNode *p = addTwoNumbers(p1,p2);

    return 0;
}

 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3