• 链表数字加和


    题目描述
    假设链表中每一个节点的值都在 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;
        }
    };
    
  • 相关阅读:
    Spark RDD操作(1)
    scala学习笔记(8): 列表的map,flatMap,zip和reduce
    (转)hadoop基本操作命令
    Mac下配置环境变量
    Spark快速入门(1)
    urllib2 request 模拟伪装浏览器
    linux下面Zookeeper的单机模式(standalone)
    linux redis安装
    python OCR 图形识别
    mysql 、慢查询、到底如何玩
  • 原文地址:https://www.cnblogs.com/lyr-2000/p/14067478.html
Copyright © 2020-2023  润新知