zoukankan      html  css  js  c++  java
  • lintcode-167-链表求和

    167-链表求和

    你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。

    样例

    给出两个链表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null

    标签

    链表 Cracking The Coding Interview 高精度

    思路

    遍历 2 个链表(即从各位开始进行加法),新建节点保存 2 个节点与上一位的进位 carry 的和,并重置 carry
    需要注意的是,若链表最高位之和大于 10 ,需要再新建最高位节点

    code

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        /**
         * @param l1: the first list
         * @param l2: the second list
         * @return: the sum list of l1 and l2 
         */
        ListNode *addLists(ListNode *l1, ListNode *l2) {
            // write your code here
            ListNode *head = new ListNode(0);
            ListNode *temp = head;
            int carry = 0;
            while (l1!= NULL && l2 != NULL) {
                int sum = l1->val + l2->val + carry;
                ListNode *node = new ListNode(sum % 10);
                carry = (sum >= 10);
                temp->next = node;
                l1 = l1->next;
                l2 = l2->next;
                temp = temp->next;
            }
            while (l1 != NULL) {
                int sum = l1->val + carry;
                ListNode *node = new ListNode(sum % 10);
                carry = (sum >= 10);
                temp->next = node;
                l1 = l1->next;
                temp = temp->next;
            }
            while (l2 != NULL) {
                int sum = l2->val + carry;
                ListNode *node = new ListNode(sum % 10);
                carry = (sum >= 10);
                temp->next = node;
                l2 = l2->next;
                temp = temp->next;
            }
            if (l1 == NULL && l2 == NULL && carry == 1) {
                ListNode *node = new ListNode(carry);
                temp->next = node;
            }
            return head->next;
        }
    };
    
  • 相关阅读:
    c#中this的一种特殊用法(extension method)
    Use a String.Format format and transform its output to its inputs?
    c#项目中遇到的add event 的一个小例子
    抽象类可以定义常量,接口中不可以定义常量
    c# 浅拷贝与深拷贝
    定制Dictionary
    c#中object字节问题
    编译过程知识的小补习
    抽象耦合
    控件集合属性遇到的问题
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7276889.html
Copyright © 2011-2022 走看看