2.Add Two Numbers&链式A+B

来源:互联网 发布:中国教育网络干部学院 编辑:程序博客网 时间:2024/06/05 01:58

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

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8


/** * 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 preHead(0),*p = &preHead;        int extra = 0;//进位        while(l1 || l2 || extra)        {            int sum = (l1?l1->val:0) + (l2?l2->val:0) + extra;            extra = sum / 10;            p->next = new ListNode(sum % 10);            p = p->next;            l1 = l1?l1->next:l1;            l2 = l2?l2->next:l2;        }                return preHead.next;                }};

/*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        if(!a && !b)            return NULL;        if(a && !b)            return a;        if(!a && b)            return b;        int carry = 0;        int sum = 0;        ListNode *sumHead = NULL;        ListNode *sumCur = NULL;        ListNode *aCur = a;        ListNode *bCur = b;        while(a || b)        {            int numA = 0;            int numB = 0;            if(a)            {                numA = a->val;                a = a->next;            }            if(b)            {                numB = b->val;                b = b->next;            }                            sum = numA+numB+carry;            if(sum>=10)            {                sum %=10;                carry = 1;            }            else            {                carry = 0;            }                        if(!sumHead)              sumCur = sumHead = new ListNode(sum);            else            {               sumCur->next = new ListNode(sum);               sumCur = sumCur->next;            }                                                          }        //注意这里!!!        if(carry == 1)        {            sumCur->next = new ListNode(1);        }                return sumHead;    }};


PS:程序员面试金典里有这个题的进阶问题,假设这些数位是正向存放的,将两个数相加(P124)。



0 0
原创粉丝点击