[LeetCode] Add Two Numbers 链表

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

 

Hide Tags
  Linked List Math
 

  这题是链表遍历问题,容易处理。
 
#include <iostream>

using namespace std;

/**

 * 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) {

        if(l1==NULL)    return l2;

        if(l2==NULL)    return l1;

        int addOne=0;

        ListNode ret(0);

        ListNode *p1=l1,*p2=l2,*pret=&ret;

        while(1){

            if(p1==NULL&&p2==NULL&&addOne==0)   break;

            if(p1==NULL&&p2==NULL){

                pret->next = new ListNode((addOne)%10);

                pret = pret->next;

                addOne = 0;

                continue;

            }

            if(p1==NULL){

                pret->next = new ListNode((p2->val + addOne)%10);

                pret = pret->next;

                addOne = (p2->val + addOne)/10;

                p2=p2->next;

                continue;

            }

            if(p2==NULL){

                pret->next = new ListNode((p1->val + addOne)%10);

                pret = pret->next;

                addOne = (p1->val + addOne)/10;

                p1=p1->next;

                continue;

            }

            pret->next = new ListNode((p1->val + p2->val + addOne)%10);

            pret = pret->next;

            addOne = (p1->val + p2->val + addOne)/10;

            p1=p1->next;

            p2=p2->next;

        }

        return ret.next;

    }

};



int main()

{



    return 0;

}

 

你可能感兴趣的:(LeetCode)