码迷,mamicode.com
首页 > 其他好文 > 详细

单链表

时间:2015-05-21 22:26:39      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

//连个链表相加//

#include "stdafx.h"

#include <iostream>
using namespace std;

// single linked list node
struct listNode{
    int val;
    listNode *next;
    listNode(int x) :val(x), next(nullptr){}
};

listNode *addTwoNumber(listNode *&L1, listNode *&L2)
{
    int value = 0;
    int carry = 0;
    listNode headNode(-1);
    listNode *pre = &headNode;

    for (listNode *pa = L1, *pb = L2;
        pa != nullptr || pb != nullptr;
        pa = pa == nullptr ? nullptr : pa->next,
        pb = pb == nullptr ? nullptr : pb->next)
    {
        value = (pa->val + pb->val + carry) % 10;
        carry = (pa->val + pb->val + carry) / 10;
        pre->next = new listNode(value);
        pre = pre->next;
    }
    if (carry > 0)
        pre->next = new listNode(carry);

    return headNode.next;
}
int _tmain(int argc, _TCHAR* argv[])
{
    listNode *L1;
    L1 = new listNode(2);
    L1->next = new listNode(4);
    L1->next->next = new listNode(3);

    listNode *L2;
    L2 = new listNode(5);
    L2->next = new listNode(6);
    L2->next->next = new listNode(7);

    listNode *L3 = addTwoNumber(L1, L2);

    cout << L3->val << L3->next->val << L3->next->next->val << L3->next->next->next->val << endl;

    system("pause");

    return 0;

}

 

单链表

标签:

原文地址:http://www.cnblogs.com/wxquare/p/4520801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!