2. Add Two Numbers 题解

来源:互联网 发布:睿易网络 编辑:程序博客网 时间:2024/06/05 14:54

2. Add Two Numbers  题解



题目描述:


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



题目链接:2. Add Two Numbers



算法描述:


           由题意知,给定两个链表,对两个链表进行相加,返回相加之后的链表,注意:链表相加时,链表中对应位置相同的元素相加,相加时注意进位。


        首先,我们构造一个结果链表 “ansList”,再用 “temp” 存储链表相加的值,对于题目中给定的两个链表,在链表头处构造指针进行遍历并相加,存储在 “temp” 中。注意:当 “temp” 的值需要进位时我们需要对下一组进行相加元素的和加一。遍历结束的条件是两个链表都为空。

        最后,结束时,如果发现 “temp” 的值为1(表示前一组相加进位),需要在结果链表尾部构造新节点存储。



代码:

/** * 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 *ansList = new ListNode(0);        int temp = 0;        ListNode* p1 = l1;        ListNode* p2 = l2;        ListNode* p3 = ansList;                while(p1!=NULL || p2!=NULL){                        if(p1!=NULL){                temp += p1->val;                p1 = p1->next;            }                        if(p2!=NULL){                temp += p2->val;                p2 = p2->next;            }                        p3->next = new ListNode(temp%10);            p3 = p3->next;            temp /= 10;        }                if(temp==1){            p3->next = new ListNode(1);        }                return ansList->next;    }};




0 0