2. Add Two Numbers

来源:互联网 发布:免费推广网络兼职平台 编辑:程序博客网 时间:2024/06/05 15:54

题目描述:

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


参考后写的代码:

class Solution {public:    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {        ListNode* result = new ListNode(0);    ListNode* cur = result;int num = 0;while(1){if(l1 != NULL){num += l1->val;l1 = l1->next;}if(l2 != NULL){num += l2->val;l2 = l2->next;}cur->val = num % 10;num /= 10;if(l1 != NULL || l2 != NULL || num){ListNode* temp = new ListNode(0);//temp->next = cur->next;cur->next = temp;cur = temp;}elsebreak;}/*while(result != NULL){cout<<result->val<<endl;result = result->next;}*/    return result;     }};
考察结构体创建链表类型的知识。算法较简单。

原创粉丝点击