leetcode第二题解法

leetcode第二题

Add Two Num

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.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

解法

关键在于对于链表知识的熟知,会用new创建空链表。注意保存头指针以及判断最后是否还有进位!!!

/**
 * 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* result=NULL;//创建最终输出结果的链表指针头
        
        int sum = ((l1!=NULL)?l1->val:0)+((l2!=NULL)?l2->val:0);
        int temp=sum/10;
        result=new ListNode(sum%10);
        ListNode *l=result;//因为要顺位输出,所以result指向指针头不变

            
        l1=l1!=NULL?l1->next:NULL;
        l2=l2!=NULL?l2->next:NULL;
        
        while(l1!=NULL||l2!=NULL){
            int num = ((l1!=NULL)?l1->val:0)+((l2!=NULL)?l2->val:0)+temp;
            temp=num/10;
            
            ListNode *ltemp=new ListNode(num%10);//中间过渡指针,用来赋值
            l->next=ltemp;
            l=ltemp;
            
            l1=l1!=NULL?l1->next:NULL;
            l2=l2!=NULL?l2->next:NULL;
        }
        if (temp == 1) {//检验:最高位相加结束后,判断是否有进位
            ListNode *ltemp=new ListNode(temp);
            l->next=ltemp;
            l=ltemp;
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43487878/article/details/87740453