zoukankan      html  css  js  c++  java
  • LeetCode445 两数相加2

    给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

    你可以假设除了数字 0 之外,这两个数字都不会以零开头。

    进阶:

    如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

    逆序处理首先应该想到栈,而不是递归,因为栈更方便,消耗空间也更少。

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    12         stack<ListNode*>s1,s2;
    13         while(l1!=nullptr){
    14             s1.push(l1);
    15             l1=l1->next;
    16         }
    17         while(l2!=nullptr){
    18             s2.push(l2);
    19             l2=l2->next;
    20         }
    21         int carry=0;
    22         ListNode* nextptr=nullptr;
    23         while(!s1.empty() || !s2.empty()){
    24             int n1=s1.empty()?0:s1.top()->val;
    25             int n2=s2.empty()?0:s2.top()->val;
    26             if(!s1.empty()) s1.pop();
    27             if(!s2.empty()) s2.pop();
    28             int sum=carry+n1+n2;
    29             if(sum>9) carry=1;
    30             else carry=0;
    31             sum%=10;
    32             ListNode* temp=new ListNode(sum);
    33             temp->next=nextptr;
    34             nextptr=temp;
    35         }
    36         if(carry){
    37             ListNode* newhaed=new ListNode(1);
    38             newhaed->next=nextptr;
    39             return newhaed;
    40         }
    41         return nextptr;
    42 
    43     }
    44 };
  • 相关阅读:
    IntelliJ IDEA 常用快捷键汇总
    Git常用命令
    org.h2.jdbc.jdbcsqlexception: database is already closed (to disable automatic closing at vm shutdown, add ";db_close_on_exit=false" to the db url) [90121-197]
    AbstractErrorController
    JSR-303
    MultipartFile
    day4
    day3
    day 2
    day1
  • 原文地址:https://www.cnblogs.com/rookiez/p/13376317.html
Copyright © 2011-2022 走看看