zoukankan      html  css  js  c++  java
  • 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

     主要是考虑进位

    Subscribe to see which companies asked this question

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    /*
     * 1.设置进位为0,并判断列表是否为空
     * 2.两个列表都不为空时,遍历,判断两个列表对应的值相加后是否大于10,大于就设置进位为1,否则为0
     * 3.一个列表为空的时候,进位+列表的对应的值,然后将剩下的添加到结果列表的尾部.
    * 4.两个列表都为空,进位位1,也添加
    */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if (NULL == l1 && NULL == l2) { return NULL; } else if (NULL == l1) { return l2; } else if (NULL == l2) { return l1; } ListNode* p1 = l1; ListNode* p2 = l2; ListNode* res_head = NULL; ListNode* res_index = NULL; int flag = 0; while (p1 != NULL && p2 != NULL) { int sum = p1->val + p2->val + flag; if (sum >= 10) { sum -= 10; flag = 1; } else { flag = 0; } ListNode* res_node = new ListNode(sum); if (NULL == res_head) { res_head = res_node; res_index = res_head; } else { res_index->next = res_node; res_index = res_node; } p1 = p1->next; p2 = p2->next; } while (p1 != NULL) { int sum = p1->val + flag; if (sum >= 10) { sum -= 10; flag = 1; } else { flag = 0; } ListNode* res_node = new ListNode(sum); res_index->next = res_node; res_index = res_node; p1 = p1->next; } while (p2 != NULL) { int sum = p2->val + flag; if (sum >= 10) { sum -= 10; flag = 1; } else { flag = 0; } ListNode* res_node = new ListNode(sum); res_index->next = res_node; res_index = res_node; p2 = p2->next; } if (0 != flag) { ListNode* res_node = new ListNode(flag); res_index->next = res_node; res_index = res_node; } return res_head; } };
  • 相关阅读:
    HDU4003 Find Metal Mineral
    POJ1125 Stockbroker Grapevine
    HDU4028The time of a day
    弱校ACM奋斗史
    POJ1236 Network of Schools
    HDU4004 The Frog's Games
    HDU4001 To Miss Our Children Time
    POJ2186 Popular Cows
    POJ1094 Sorting It All Out
    hadoop2.7.1单机和伪集群的搭建0
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5090387.html
Copyright © 2011-2022 走看看