道阻且长,行则将至,走慢一点没关系,不停下就好了.|

Ac_c0mpany丶

园龄:3年7个月粉丝:6关注:3

2023-12-07 19:42阅读: 4评论: 0推荐: 0

[LeetCode Hot 100] LeetCode2. 两数相加

题目描述

思路:模拟

每次3个数相加:l1链表的值 + l2链表的值 + 进位
如果 l1链表不为空 或者 l2链表不为空 或者 进位不为0 我们就执行循环
那么和存储的是 t % 10
进位就是t / 10
因为题目需要创造一条链表,所以我们创建一个dummy结点的话会方便一点。

方法一:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 记录进位
        int t = 0;
        ListNode p = l1, q = l2;
        // 因为要创造新的链表,所以新建dummy结点
        ListNode dummy = new ListNode();
        ListNode cur = dummy;

        while (p != null || q != null || t != 0) {
            if (p != null) {
                t += p.val;
                p = p.next;
            } 
            if (q != null) {
                t += q.val;
                q = q.next;
            }
            cur.next = new ListNode(t % 10);
            cur = cur.next;
            t /= 10;
        }

        return dummy.next;     
   }
}

本文作者:Ac_c0mpany丶

本文链接:https://www.cnblogs.com/keyongkang/p/17883811.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Ac_c0mpany丶  阅读(4)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 You Are My Sunshine REOL
You Are My Sunshine - REOL
00:00 / 00:00
An audio error has occurred.

作曲 : Traditional

You are my sunshine

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away

The other night, dear,

When I lay sleeping

I dreamed I held you in my arms.

When I awoke, dear,

I was mistaken

So I hung my head and cried.

You are my sunshine,

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away.

You are my sunshine,

My only sunshine

You make me happy

When skies are gray.

You'll never know, dear

How much I love you

Please don't take my sunshine away

Please don't take my sunshine away.

Please don't take my sunshine away.