zoukankan      html  css  js  c++  java
  • 2. Add Two Numbers

    题目链接:https://leetcode.com/problems/add-two-numbers/

    解题思路:

    1、我们不考虑反向输出之类的,直接按照正常的思路。如果第一个链表的第一个数+第二个链表的第一个数小于10,我们把它存起来。如果大于等于10,我们就要进位,进到后一位去。

    正常的加法是向前进一位,那这里是链表逆序,所以往后进一位,temp=temp/10。

    2、链表定义的时候定义一个头结点,这样方便理解。

    3、temp值是存每一位的和用的。

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution {
    10     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    11         
    12         
    13         if(l1==null)
    14                  return l2;
    15         if(l2==null)
    16                  return l1;
    17              
    18         ListNode head = new ListNode(122);//定义头结点
    19         ListNode p =head;
    20         int temp=0;
    21         while(l1!=null || l2!=null || temp!=0)
    22         {
    23             if(l1!=null)
    24             {
    25                 temp+=l1.val;
    26                 l1=l1.next;
    27             }
    28             if(l2!=null)
    29             {
    30                 temp+=l2.val;
    31                 l2=l2.next;
    32             }
    33 
    34             p.next = new ListNode(temp%10);
    35             p = p.next;
    36             temp=temp/10;
    37         }
    38         return head.next;  
    39     }
    40 }
  • 相关阅读:
    【poj1655】Balancing Act
    yargs.js用法
    8、typescript
    7、typescript
    6、typescript
    5、typescript
    4、typescript
    3、typescript
    2、typescript
    1、typescript
  • 原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/10821901.html
Copyright © 2011-2022 走看看