Add Two Numbers

来源:互联网 发布:渲染软件哪个好 编辑:程序博客网 时间:2024/05/28 03:04

题意:
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 *link1=l1,*link2=l2,*linkAns=new ListNode(0);        int carry=0;        ListNode *newLink=linkAns;        while(link1!=NULL || link2!=NULL){// 这种方法简便            if(link1!=NULL){                carry+=link1->val;                link1=link1->next;            }            if(link2!=NULL){                carry+=link2->val;                link2=link2->next;            }            ListNode *link=new ListNode(carry%10);            carry/=10;            newLink->next=link;            newLink=link;        }        if(carry){            ListNode *link=new ListNode(carry);            newLink->next=link;        }        return linkAns->next;       }};
0 0
原创粉丝点击