zoukankan      html  css  js  c++  java
  • [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;
    }
  • 相关阅读:
    python知识合集
    可拖动的DIV
    JavaScript创建对象
    JavaScript prototype
    CSS media queries
    JavaScript作用域链
    JavaScript包装对象
    贫下中农版jQuery
    JavaScript 命名空间
    z-index 应用简单总结
  • 原文地址:https://www.cnblogs.com/Azhu/p/4239110.html
Copyright © 2011-2022 走看看