zoukankan      html  css  js  c++  java
  • [LeetCode] #2 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

    本题其实就是两个链表合并,不同的就是要考虑进位。时间:110ms

    代码如下:

    /**
     * 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;
            ListNode *l3=NULL, *node;
            ListNode *pHead1 = l1, *pHead2 = l2, *pHead3 = l3;
            int up = 0;
            while (pHead1 != NULL && pHead2 != NULL){
                node = new ListNode(pHead1->val + pHead2->val + up);
                up = node->val / 10;
                node->val = node->val %10;
                if (l3 == NULL){
                    l3 = pHead3 = node;
                }
                else{
                    pHead3->next = node;
                    pHead3 = pHead3->next;
                }
                pHead1 = pHead1->next;
                pHead2 = pHead2->next;
            }
            while (pHead1 != NULL){
                node = new ListNode(pHead1->val + up);
                up = node->val / 10;
                node->val = node->val % 10;
                pHead3->next = node;
                pHead1 = pHead1->next;
                pHead3 = pHead3->next;
            }
            while (pHead2 != NULL){
                node = new ListNode(pHead2->val + up);
                up = node->val / 10;
                node->val = node->val % 10;
                pHead3->next = node;
                pHead2 = pHead2->next;
                pHead3 = pHead3->next;
            }
            if (up > 0){
                node = new ListNode(up);
                pHead3->next = node;
            }
            return l3;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    数据结构之 栈的应用 括号匹配
    全排列算法与全组合算法
    数据结构高分笔记 第二章综合应用题
    数据结构之 队列的操作与实现
    [置顶] 数据结构之 队列的操作与实现
    php数据库操作类
    php分页类
    [置顶] 数据结构之 链栈的实现
    MySQL数据库应用 从入门到精通 学习笔记
    Linux服务器上使用curl命令发送报文
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4394460.html
Copyright © 2011-2022 走看看