zoukankan      html  css  js  c++  java
  • 链表数字加和

    题目描述
    假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
    给定两个这种链表,请生成代表两个整数相加值的结果链表。
    例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
    示例1
    输入
    复制
    [9,3,7],[6,3]
    返回值
    复制
    {1,0,0,0}
    备注:

     /**
     * struct ListNode {
     *	int val;
     *	struct ListNode *next;
     * };
     */
    
    class Solution {
    public:
        /**
         * 
         * @param head1 ListNode类 
         * @param head2 ListNode类 
         * @return ListNode类
         */
        ListNode* addInList(ListNode* head1, ListNode* head2) {
            // write code here
            head1 = reverse(head1),head2 = reverse(head2);
            ListNode* h= new ListNode(0),*p = h;
            int carry = 0;
            while (head1 || head2) {
                int a = head1? head1->val:0,b = head2? head2 ->val:0;
                int sum = a+b+carry;
                carry = sum/10,sum%=10;
                ListNode * cur = new ListNode(sum);
                p -> next = cur;
                if (head1) head1 = head1->next;
                if (head2) head2 = head2 ->next;
                p = p->next;
               
                
            }
            if(carry) {
                p ->next = new ListNode(carry);
            }
            ListNode * res = h ->next;
            delete h;
            
            
            return reverse(res);
        }
        
        ListNode * reverse(ListNode *p) {
            ListNode *res = NULL,*pre = nullptr,*next=NULL;
            while(p) {
                next = p -> next,p ->next =  pre, pre = p, p = next;
            }
            return pre;
        }
    };
    
  • 相关阅读:
    前端 整理的待学习技术点
    为Xamarin更好的开发而改写的库
    C#函数式编程之可选值
    C#函数式编程之序列
    C#函数式编程之标准高阶函数
    C#函数式编程之递归调用
    C#函数式编程之缓存技术
    C#函数式编程之惰性求值
    C#函数式编程之部分应用
    Xamarin.Android之动画
  • 原文地址:https://www.cnblogs.com/lyr-2000/p/14067478.html
Copyright © 2011-2022 走看看